How to check if an object has a particular method?

别等时光非礼了梦想. 提交于 2019-12-03 05:53:53

A simple option is to declare an interface with just the method you want to check for and then do a type assert against your type like;

 i, ok := myInstance.(InterfaceImplementingThatOneMethodIcareAbout)
 // inline iface delcataration example
 i, ok = myInstance.(interface{F()})

You likely want to use the reflect package if you plan to do anything too crazy with your type; http://golang.org/pkg/reflect

st := reflect.TypeOf(myInstance)
m, ok := st.MethodByName("F")
if !ok {
    // method doesn't exist
}
// do something like invoke m

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

if correctobj, ok := obj.(interface{methodName()}); ok { 
  correctobj.methodName() 
} 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!