duandanai6470 2014-11-25 16:26
浏览 36
已采纳

是否有必要使用类型断言来访问接口返回的类型的值?

When I have a function that returns an interface type, the returned value doesn't work as I would expect. That is, it acts strictly as the defined interface, and to access the methods and values not defined in the interface, I have to do a type assertion. Why?

Consider the following sample code:

package main

import (
    "fmt"
)

type Frobnicator interface {
    Frobnicate()
}

type Foo struct {
    Value  string
}

func (f *Foo) Frobnicate() {
    fmt.Printf("The value is %s
", f.Value)
}

func fooFactory () Frobnicator {
    return &Foo{"chicken"}
}

func main() {
    foo := fooFactory( )
    foo.Frobnicate()
    // foo.Value undefined (type Frobnicator has no field or method Value)
    // fmt.Printf("foo value = %s
", foo.Value)
    bar := foo.(*Foo)
    fmt.Printf("bar value = %s
", bar.Value)
}

Is there a better, easier, more idiomatic way to get at foo.Value? Or is a type assertion really the best way?

  • 写回答

2条回答 默认 最新

  • drob50257447 2014-11-25 16:41
    关注

    Not sure what to answer here. Maybe there is a misconception what interface types are. Interface types are absolutely normal types. And you can do with a interface value what the interface says: Invoke the interface methods. For a struct type you may access fields and invoke interface methods as defined by the struct type. So everything is plain and simple: A type allows what it allows, no matter whether interface or struct.

    It now happens that a value of interface type may contain some struct value (say). Up to now this is hidden. Type asserting reveals the struct value (and there is no more interface). You may hide an other struct value in the interface (given it implements the right methods) this might not have a Value field. This makes it clear that you cannot access the Value field without a type assertion, because it might not be there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)