2
[Golang] Call a Struct and its Method by Name
source link: http://siongui.github.io/2016/02/11/go-call-a-struct-and-its-method-by-name/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[Golang] Call a Struct and its Method by Name
February 11, 2016
Call a function (method) of a struct by name during run-time in Golang. (run-time reflection)
package main import ( "fmt" "math" "reflect" ) type Circle struct { r float64 } func (c *Circle) Area() float64 { return math.Pi * c.r * c.r } func main() { c := Circle{1.2} // call Area() method fmt.Println(c.Area()) // call Area() method by Name v := reflect.ValueOf(&c).MethodByName("Area").Call([]reflect.Value{}) fmt.Println(v[0].Float()) }
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK