dimanche 5 avril 2020

Golang reflection MethodByName()

I write the code that fills data structures depending on its type. I need to call nested struct function if it exists.

Why I get zero value looking for function while the field is correct?

type (

    SomeData struct {
        Val NestedType
    }

    NestedType struct {
        V1 string
    }
)

func (t *NestedType) FillData(v int) {
    t.V1 = fmt.Sprintf("I hate %v", v)
}

func main() {


    reflect.ValueOf(&i.Val).MethodByName("FillData").Call([]reflect.Value{reflect.ValueOf(555)})
    fmt.Println(i) /// here we get 555


    // BUT!

    v := 666

    fVal := newObj.Elem().FieldByName("Val")
    fmt.Println( "fVal.NumField():", fVal.NumField()) //fVal.NumField(): 1


    f := fVal.MethodByName("FillData")
    f.Call([]reflect.Value{reflect.ValueOf(v)}) //panic: reflect: call of reflect.Value.Call on zero Value


}




Aucun commentaire:

Enregistrer un commentaire