I have found a function call MethodByName()
here http://golang.org/pkg/reflect/#Value.MethodByName but it's not exactly what I want! (maybe because I don't know how to use it ... I cannot find any example with it). What I want is:
type MyStruct struct {
//some feilds here
}
func (p *MyStruct) MyMethod {
println("My statement.");
}
CallFunc("MyStruct", "MyMethod");
//print out My statement."
So I guess, first I need something like StructByName()
and after that use it for MethodByName()
, is that right!?
Really code need check the method's input number or method it self whether validly . You can reference this http://gowalker.org/reflect#Type
ret
byreflect.Value.Interface()
and be careful the Ptr type; or You can use
SomeInterface{}
instead of directly useinterface{}
to ensure this "any" type, like thisso this is OK
but
can't be compiled because
NotAnShape
isn't a Shape.If you can't sure which the first type will be used at compile time, you can build an map to store all possible type, like this.
To call a method on an object, first use
reflect.ValueOf
. Then find the method by name, and then finally call the found method. For example:}
gist invoke struct method with error handling