Call a Struct and its Method by name in Go?

后端 未结 4 678
我在风中等你
我在风中等你 2020-12-02 05:47

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 kn

4条回答
  •  無奈伤痛
    2020-12-02 06:20

    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:

    package main
    
    import "fmt"
    import "reflect"
    
    type T struct {}
    
    func (t *T) Foo() {
        fmt.Println("foo")
    }
    
    func main() {
        var t T
        reflect.ValueOf(&t).MethodByName("Foo").Call([]reflect.Value{})
    }
    

提交回复
热议问题