【发布时间】:2015-04-16 19:48:32
【问题描述】:
在 Go 中,如何检查对象是否响应方法?
例如,在 Objective-C 中,这可以通过以下方式实现:
if ([obj respondsToSelector:@selector(methodName:)]) { // if method exists
[obj methodName:42]; // call the method
}
【问题讨论】:
标签: go go-reflect
在 Go 中,如何检查对象是否响应方法?
例如,在 Objective-C 中,这可以通过以下方式实现:
if ([obj respondsToSelector:@selector(methodName:)]) { // if method exists
[obj methodName:42]; // call the method
}
【问题讨论】:
标签: go go-reflect
一个简单的选择是仅使用您要检查的方法声明一个接口,然后对您的类型进行类型断言,例如;
i, ok := myInstance.(InterfaceImplementingThatOneMethodIcareAbout)
// inline iface declaration example
i, ok = myInstance.(interface{F()})
如果您打算对您的类型做任何过于疯狂的事情,您可能想要使用 reflect 包; http://golang.org/pkg/reflect
st := reflect.TypeOf(myInstance)
m, ok := st.MethodByName("F")
if !ok {
// method doesn't exist
} else {
// do something like invoke m.F
}
【讨论】:
m,既然是reflect.Method类型呢?
如果 obj 是 interface{},你可以使用 Go 类型断言:
if correctobj, ok := obj.(interface{methodName()}); ok {
correctobj.methodName()
}
【讨论】:
interface{methodName()} 在类型断言中起作用? (为什么)interface{methodName()} 是类型匹配而不是简单的interface{} 并且(为什么)即使接口有其他方法它也能工作?
correctobj.methodName()值呢? x:=correcorrectobj.methodName() 给出错误 correctobj.methodName() used as value
methodName 在类型断言中的签名没有返回值。如果签名是 methodName() int,则不会发生此错误。
obj.(T) 为真。在 T 为 interface{methodName()} 的情况下,断言为如果 obj 至少有一个列出的方法,则为 true。在 T 为interface{} 的情况下,类型断言总是微不足道的,因为没有方法要求需要满足。 Go playground.
除了@evanmcdonnal 在接口大括号{write_function_declaration_here} 内的解决方案之外,您将编写函数声明
if correctobj, ok := obj.(interface{methodName(func_arguments_here)(return_elements_here)}); ok {
x,... := correctobj.methodName()
}
即
package main
import "fmt"
type test struct {
fname string
}
func (t *test) setName(name string) bool {
t.fname = name
return true
}
func run(arg interface{}) {
if obj, ok := arg.(interface{ setName(string) bool });
ok {
res := obj.setName("Shikhar")
fmt.Println(res)
fmt.Println(obj)
}
}
func main() {
x := &test{
fname: "Sticker",
}
fmt.Println(x)
run(x)
}
【讨论】: