作者:羊鲜鸡美蟹肥 | 来源:互联网 | 2023-05-28 10:12
我读过"Effective Go"和其他问答:golang界面兼容性编译类型检查,但是我无法正确理解如何使用这种技术.
请看例子:
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
}
是否有任何简单的方法(例如,不使用反射)检查值,如果它实现了一个接口?
1> Dean Elbaz..:
如果您不知道值的类型,则只需检查值是否实现接口.如果类型已知,则该检查由编译器自动完成.
如果你真的想要检查,你可以使用你给出的第二种方法:
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
,它将编译并不执行任何操作