vendredi 16 mars 2018

Golang: Set value of interface to struct field of type pointer to struc via reflection

I'm currently struggling with reflection in go. I'm trying to set struc.field = &otherStruc. However, I have to use reflection, and otherStruc is of type interface{}.

The error I'm getting is:

reflect.Set: value of type main.StrucB is not assignable to type *main.StrucB

struc is known. The (real) type of otherStruc is not known, but it is guaranteed, that the assignment is safe (the struc type is identical).

Code:

type StrucA struct {
    Field *StrucB
}

type StrucB struct {}

func main() {
    a := StrucA{}
    var b interface{} = StrucB{}
    //above is set

    // Target: Set a.Field = &b
    reflect.ValueOf(&a).Elem().FieldByName("Field").Set(reflect.ValueOf(b)) // reflect.Set: value of type main.StrucB is not assignable to type *main.StrucB
}

Playground: https://play.golang.org/p/LR_RgfBzsxa

I have tested a lot of different stuff, but I'm unable to solve it.

Thanks for the help

cheers Chris





Aucun commentaire:

Enregistrer un commentaire