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:@selector(methodName:)]) { // if method exists [obj methodName:42]; // call the method }
The first way is to invoke object. hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise. hasOwnProperty() searches only within the own properties of the object.
You can use Object. values(): The Object. values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
How to Check if an Object Has a key in JavaScript with the in Operator. You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain.
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 declaration 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 } else { // do something like invoke m.F }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With