lundi 9 décembre 2019

golang reflection to set first value of a struct to its zero value

go playground: https://play.golang.org/p/ck3PtydW3YT

I have a struct like:

type Input struct {
    InputA *InputA
    InputB *InputB
    InputC *InputC
}

I'm trying to use reflection to set the first value (in this case, *InputA) to its zero value (&InputA{}), but it's not working:

    actionInput = Input{}
    v := reflect.ValueOf(actionInput)

    i := 0
    typ := v.Field(i).Type()

    inputStruct := reflect.New(typ).Elem().Interface()

    reflect.ValueOf(&actionInput).Elem().Field(i).Set(reflect.ValueOf(inputStruct))

I'm guessing this is because it's a pointer, but I'm not sure how to work around that





Aucun commentaire:

Enregistrer un commentaire