我读过“Effective Go”和其他类似这样的问答:golang接口合规性编译类型检查 https://stackoverflow.com/questions/17994519/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
}
如果它实现了接口,是否有任何简单的方法(例如不使用反射)检查值?
如果您不知道值的类型,则只需检查该值是否实现接口。
如果类型已知,则编译器会自动完成该检查。
如果您确实想检查,可以使用您提供的第二种方法:
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
,但由于变量名称是_
它被忽视了。
If MyType
实施的Somether
,它会编译并且不执行任何操作
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)