为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
白板的微信 2021-09-27 21:24:43
在 Go 中,如何检查对象是否响应方法?例如,在 Objective-C 中,这可以通过执行以下操作来实现:if ([obj respondsToSelector:@selector(methodName:)]) { // if method exists  [obj methodName:42]; // call the method}

3 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

如果 obj 是一个,interface{}你可以使用 Go 类型断言:


if correctobj, ok := obj.(interface{methodName()}); ok { 

  correctobj.methodName() 


查看完整回答
反对 回复 2021-09-27
?
忽然笑

TA贡献1806条经验 获得超5个赞

除了接口大括号{write_function_declaration_here}内@evanmcdonnal的解决方案之外,您将编写函数声明


if correctobj, ok := obj.(interface{methodName(func_arguments_here)(return_elements_here)}); ok { 

 x,... := correctobj.methodName() 

IE


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)


}


查看完整回答
反对 回复 2021-09-27

添加回答

代码语言

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信