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
andy
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