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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!