我读过“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 许可协议
如果您不知道值的类型,则只需检查该值是否实现了接口。如果类型已知,则该检查由编译器自动完成。
如果你真的想检查,你可以用你给的第二种方法来做:
这会在编译时出错:
您在这里所做的是将
MyType
类型的指针(和nil
值)分配给类型为Somether
的变量_
但是---
它被忽略了。如果
MyType
实现Somether
,它会编译并且什么都不做