检查value是否实现接口的说明 [英] Explanation of checking if value implements interface
问题描述
我读过Effective Go和其他Q&如下: golang接口合规性编译类型检查,但是我无法正确理解如何使用这种技术。
I've read "Effective Go" and other Q&As like this: golang interface compliance compile type check , but nonetheless I can't understand properly how to use this technique.
请参阅示例:
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
}
有没有简单的方法(例如,不使用反射)检查值是否实现了接口?
Is there any simple ways (eg without using reflection) check value if it implements an interface?
推荐答案
您只需检查一个值是否实现了如果你不知道值的类型接口。
如果类型已知,则该检查由编译器自动完成。
You only have to check if a value implements an interface if you don't know the value's type. If the type is known, that check is automatically done by the compiler.
如果你真的想要检查,你可以使用第二种方法你给了:
If you really want to check anyways, you can do it with the second method you gave:
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 <的指针/ code>键入(并且
nil
value)到类型 Somether
的变量,但是因为变量名称是 _
它被忽略。
What you are doing here, is assigning a pointer of MyType
type (and nil
value) to a variable of type Somether
, but since the variable name is _
it is disregarded.
如果 MyType
已实施 Somether
,它会编译并且什么都不做
If MyType
implemented Somether
, it would compile and do nothing
这篇关于检查value是否实现接口的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!