How to assign a value to another of the same type when both are passed as interface{}?

95 Views Asked by At

In other words - how to write the body of the function assignInterfaceTo, so that the test passes?

type testreq struct {
    V int32
}

func assignInterfaceTo(x, y interface{}) {}

func TestAssignInterfaceTo(t *testing.T) {
    x := &testreq{V: 1}
    y := &testreq{V: 2}
    func(arg interface{}) {
        assignInterfaceTo(arg, y)
    }(x)
    if x.V != y.V {
        t.Fatalf("\nwant: %d\nhave: %d", y.V, x.V)
    }
}

Constraints:

  • it's known that x and y are of same type, if this helps (no need to check if the type is the same)
  • type can be a pointer to arbitrary struct, type of struct is not known in advance, so you can't use switch / type assertion
  • marshal/unmarshal to json or other encodings is not an option

My attempts:

  • reflect.ValueOf(x).Set(reflect.ValueOf(y)):

panic: reflect: reflect.Value.Set using unaddressable value

  • reflect.Copy(reflect.ValueOf(x), reflect.ValueOf(y)):

panic: reflect: call of reflect.Copy on ptr Value

0

There are 0 best solutions below