猿问

如何检查对象是否具有特定方法?

在 Go 中,如何检查对象是否响应方法?


例如,在 Objective-C 中,这可以通过执行以下操作来实现:


if ([obj respondsToSelector:@selector(methodName:)]) { // if method exists

  [obj methodName:42]; // call the method

}


白板的微信
浏览 169回答 3
3回答

慕的地6264312

如果 obj 是一个,interface{}你可以使用 Go 类型断言:if correctobj, ok := obj.(interface{methodName()}); ok {   correctobj.methodName() } 

忽然笑

除了接口大括号{write_function_declaration_here}内@evanmcdonnal的解决方案之外,您将编写函数声明if correctobj, ok := obj.(interface{methodName(func_arguments_here)(return_elements_here)}); ok {  x,... := correctobj.methodName() } IEpackage mainimport "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)}
随时随地看视频慕课网APP

相关分类

Go
我要回答