pointers - How to pass a struct's method as a parameter into another function using golang -
sorry, post question again.
i have been read solution before ask question. think can not me because question how pass function parameter? don't want call it.
i want pass function can't edit (or don't want edit), , want use string variable point function
funcname := "go" m.set(t.funcname)
i think different question call struct , method name in go?
for example
i have function like:
type context struct{} type myclass struct{} type handler func (c *context) func (r *myclass) set(ch handler) { }
i can use way:
type testclass struct {} func (t *testclass) go(c *context){ println("hello"); } t := &testclass{} m := &myclass{} m.set(t.go)
and question is
type testclass struct{} func (t *testclass) go(c *context){ println("hello"); } t := &testclass{} m := &myclass{} funcname := "go" m.set(t.funcname)
any way can this?
reflect?or what?
if impossible, there other ways this?
thanks
you can method name using reflect package. here's function handler
given name:
func handlerbyname(v interface{}, name string) (handler, error) { m := reflect.valueof(v).methodbyname(name) if !m.isvalid() { return nil, errors.new("method not found") } h, ok := m.interface().(func(*context)) if !ok { return nil, errors.new("method not handler") } return h, nil }
here's how use function:
h, err := handlerbyname(t, "go") if err != nil { // handle error } m.set(h)
note function returned handlerbyname reflection wrapper around original function (thanks @oneofone pointing out). calling wrapper slow compared calling function directly.
Comments
Post a Comment