jeudi 16 mai 2019

Set a field value with Go reflection of a non-pointer receiver interface implementation

The goal is to set a new value of the a.Stringer.Name using Go reflection.

type A struct {
  Stringer fmt.Stringer
}

type MyStringer struct {
  Name string
}
func (m MyStringer) String() string {
  return m.Name
}

a := &A{
  Stringer: MyStringer {
    Name: "Adam",
  },
}

// The following code panics with: "reflect: reflect.Value.Set using unaddressable value"
reflect.ValueOf(a).Elem().
FieldByName("Stringer").Elem().
FieldByName("Name").Set(reflect.ValueOf("New name"))

Everything works fine with concrete types though:

type B struct {
  Stringer MyStringer
}

b := &B{
  Stringer: MyStringer {
    Name: "Adam",
  },
}

reflect.ValueOf(b).Elem().
FieldByName("Stringer").
FieldByName("Name").Set(reflect.ValueOf("New value"))

How to make the interface struct addressable? Am i missing something?





Aucun commentaire:

Enregistrer un commentaire