How to check if an object has a particular method?

前端 未结 2 1278
终归单人心
终归单人心 2021-01-01 14:07

In Go, how do you check if an object responds to a method?

For example, in Objective-C this can be achieved by doing:

if ([obj respondsToSelector:@se         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 14:29

    If obj is an interface{} you can use Go type assertions:

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

提交回复
热议问题