From df897aec9dc4228e585e8127b4db026d506d2b3c Mon Sep 17 00:00:00 2001 From: Muhammad Noor Misyuari <12197761+misyuari@users.noreply.github.com> Date: Thu, 19 Oct 2023 14:13:09 +0700 Subject: [PATCH] fix: decode struct with pointer must be nil (#473) --- decode_test.go | 7 +++++++ internal/decoder/ptr.go | 1 + 2 files changed, 8 insertions(+) diff --git a/decode_test.go b/decode_test.go index df914ed..8f32ced 100644 --- a/decode_test.go +++ b/decode_test.go @@ -197,6 +197,13 @@ func Test_Decoder(t *testing.T) { assertEq(t, "interface{}", v.F, nil) assertEq(t, "nilfunc", true, v.G == nil) }) + t.Run("struct.pointer must be nil", func(t *testing.T) { + var v struct { + A *int + } + json.Unmarshal([]byte(`{"a": "alpha"}`), &v) + assertEq(t, "struct.A", v.A, (*int)(nil)) + }) }) t.Run("interface", func(t *testing.T) { t.Run("number", func(t *testing.T) { diff --git a/internal/decoder/ptr.go b/internal/decoder/ptr.go index de12e10..ae22994 100644 --- a/internal/decoder/ptr.go +++ b/internal/decoder/ptr.go @@ -85,6 +85,7 @@ func (d *ptrDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.P } c, err := d.dec.Decode(ctx, cursor, depth, newptr) if err != nil { + *(*unsafe.Pointer)(p) = nil return 0, err } cursor = c