From edeaeddb2d51868df8c6ff2d8a218b527aeaf5fd Mon Sep 17 00:00:00 2001 From: Chotow Date: Wed, 25 Oct 2023 20:49:51 +0800 Subject: [PATCH] fix(reflect): not assignable to type --- decode_value.go | 2 +- msgpack_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/decode_value.go b/decode_value.go index 556c6ac..a6db402 100644 --- a/decode_value.go +++ b/decode_value.go @@ -128,7 +128,7 @@ func ptrValueDecoder(typ reflect.Type) decoderFunc { return func(d *Decoder, v reflect.Value) error { if d.hasNilCode() { if !v.IsNil() { - v.Set(d.newValue(typ)) + v.Set(reflect.Zero(v.Type())) } return d.DecodeNil() } diff --git a/msgpack_test.go b/msgpack_test.go index 2beb768..c3872c0 100644 --- a/msgpack_test.go +++ b/msgpack_test.go @@ -528,3 +528,28 @@ func TestEncodeWrappedValue(t *testing.T) { require.Nil(t, msgpack.NewEncoder(&buf).Encode(v)) require.Nil(t, msgpack.NewEncoder(&buf).Encode(c)) } + +func TestPtrValueDecode(t *testing.T) { + type Foo struct { + Bar *int + } + + b, err := msgpack.Marshal(Foo{}) + require.Nil(t, err) + + bar1 := 123 + foo := Foo{Bar: &bar1} + + err = msgpack.Unmarshal(b, &foo) + require.Nil(t, err) + require.Nil(t, foo.Bar) + + bar2 := 456 + b, err = msgpack.Marshal(Foo{Bar: &bar2}) + require.Nil(t, err) + + err = msgpack.Unmarshal(b, &foo) + require.Nil(t, err) + require.NotNil(t, foo.Bar) + require.Equal(t, *foo.Bar, bar2) +}