Chris
Chris

Reputation: 58

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

I'm trying to set struct.field = &otherStruct. However, I have to use reflection, and otherStruct is of type interface{}.

The error I'm getting is:

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

struct is known. The (real) type of otherStruct is not known, but it is guaranteed, that the assignment is safe (the struct 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.

Upvotes: 4

Views: 5155

Answers (1)

JimB
JimB

Reputation: 109332

You first need to allocate a pointer to the type of b, in order to have somewhere to copy the value. Once you have a pointer value, you can set that to Field in a:

field := reflect.New(reflect.TypeOf(b))
field.Elem().Set(reflect.ValueOf(b))
reflect.ValueOf(&a).Elem().FieldByName("Field").Set(field)

https://play.golang.org/p/6-GNSEq0tw3

Upvotes: 7

Related Questions