From f3aded9b1218b2e465fdb65b256362ac53f76b54 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Tue, 30 Mar 2021 19:37:19 +0900 Subject: [PATCH] Fix detection of indirect field --- cover_string_test.go | 12 ++++++++++++ internal/encoder/compiler.go | 10 +++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/cover_string_test.go b/cover_string_test.go index 1d0f389..9d9d882 100644 --- a/cover_string_test.go +++ b/cover_string_test.go @@ -32,6 +32,18 @@ func TestCoverString(t *testing.T) { name string data interface{} }{ + { + name: "PtrHeadStringComplicated", + data: &struct { + X *struct { + A string + B []string + } + }{X: &struct { + A string + B []string + }{A: "hello", B: []string{"a", "b"}}}, + }, { name: "String", data: string("a"), diff --git a/internal/encoder/compiler.go b/internal/encoder/compiler.go index 76751a9..bf35a14 100644 --- a/internal/encoder/compiler.go +++ b/internal/encoder/compiler.go @@ -1399,7 +1399,15 @@ func compileStruct(ctx *compileContext, isPtr bool) (*Opcode, error) { valueCode.Indirect = indirect } } else { - valueCode.Indirect = indirect + if indirect { + // if parent is indirect type, set child indirect property to true + valueCode.Indirect = indirect + } else { + // if parent is not indirect type and child have only one field, set child indirect property to false + if i == 0 && valueCode.NextField != nil && valueCode.NextField.Op == OpStructEnd { + valueCode.Indirect = indirect + } + } } key := fmt.Sprintf(`"%s":`, tag.Key) escapedKey := fmt.Sprintf(`%s:`, string(AppendEscapedString([]byte{}, tag.Key)))