检查值是否实现接口的解释

新手上路,请多包涵

我读过“Effective Go”和其他类似这样的问答: golang interface compliance compile type check ,但我仍然无法正确理解如何使用这种技术。

请看例子:

 type Somether interface {
    Method() bool
}

type MyType string

func (mt MyType) Method2() bool {
    return true
}

func main() {
    val := MyType("hello")

    //here I want to get bool if my value implements Somether
    _, ok := val.(Somether)
    //but val must be interface, hm..what if I want explicit type?

    //yes, here is another method:
    var _ Iface = (*MyType)(nil)
    //but it throws compile error
    //it would be great if someone explain the notation above, looks weird
}

如果它实现了接口,是否有任何简单的方法(例如不使用反射)检查值?

原文由 Timur Fayzrakhmanov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 477
2 个回答

如果您不知道值的类型,则只需检查该值是否实现了接口。如果类型已知,则该检查由编译器自动完成。

如果你真的想检查,你可以用你给的第二种方法来做:

 var _ Somether = (*MyType)(nil)

这会在编译时出错:

 prog.go:23: cannot use (*MyType)(nil) (type *MyType) as type Somether in assignment:
    *MyType does not implement Somether (missing Method method)
 [process exited with non-zero status]

您在这里所做的是将 MyType 类型的指针(和 nil 值)分配给类型为 Somether 的变量 _ 但是 --- 它被忽略了。

如果 MyType 实现 Somether ,它会编译并且什么都不做

原文由 Dean Elbaz 发布,翻译遵循 CC BY-SA 3.0 许可协议

以下将起作用:

 val:=MyType("hello")
var i interface{}=val
v, ok:=i.(Somether)

原文由 Alpha 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题