How to check if an object has a particular method?

前端 未结 2 1241
终归单人心
终归单人心 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条回答
  •  别那么骄傲
    2021-01-01 14:54

    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
    

提交回复
热议问题