lundi 11 octobre 2021

invoke a method from a new instance (reflect.New) with reflection in golang

good day together I want to instantiate an object in Go using reflection and call a method on it. However, I have no idea how to do this. I have tried something, but it does not work.

type foo struct {
    name string
}

func (f *foo) Bar() {
    f.name = "baz"
    fmt.Println("hi " + f.name)
}

func main() {
    t := reflect.TypeOf(&foo{})
    fooElement := reflect.New(t).Elem()
    fooElement.MethodByName("Bar").Call([]reflect.Value{})
}




Aucun commentaire:

Enregistrer un commentaire