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
}
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
}
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 obj is an interface{}
you can use Go type assertions:
if correctobj, ok := obj.(interface{methodName()}); ok {
correctobj.methodName()
}
Just in addition to @evanmcdonnal's solution inside the interface braces {write_function_declaration_here}, you will write the function declaration
if correctobj, ok := obj.(interface{methodName(func_arguments_here)(return_elements_here)}); ok {
x,... := correctobj.methodName()
}
i.e.
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)
}