lundi 24 septembre 2018

Using reflect to call method of struct inside struct method

How can I use reflect to call method of struct, inside a struct method? e.g:

package main

import "fmt"
import "reflect"

type T struct{}

func (t *T) New() {
    value := getDynamicValue()
    method := reflect.ValueOf(&t).MethodByName(value)
    fmt.Println(method)
}

func (t *T) fake() {
    fmt.Println("Fake!")
}

func main() {
    var t T
    t.New()
}

func getDynamicValue() string {
    return "fake"
}

The following code will print <invalid reflect.Value> even though fake exists.

Thanks in advance! :)





Aucun commentaire:

Enregistrer un commentaire