From 5b5f6e32a8fa90b185daf7f30aeed01157a26656 Mon Sep 17 00:00:00 2001 From: Tom <73077675+tmzane@users.noreply.github.com> Date: Wed, 8 May 2024 17:22:35 +0300 Subject: [PATCH] fix: check whether a pointer-type implements a Marshaler interface (#94) --- musttag.go | 2 +- testdata/src/tests/tests.go | 28 +++++++++++----------------- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/musttag.go b/musttag.go index 7be684f..70c8420 100644 --- a/musttag.go +++ b/musttag.go @@ -273,7 +273,7 @@ func implementsInterface(typ types.Type, ifaces []string, imports []*types.Packa if !ok { continue } - if types.Implements(typ, iface) { + if types.Implements(typ, iface) || types.Implements(types.NewPointer(typ), iface) { return true } } diff --git a/testdata/src/tests/tests.go b/testdata/src/tests/tests.go index 25461a1..0d4e766 100644 --- a/testdata/src/tests/tests.go +++ b/testdata/src/tests/tests.go @@ -131,23 +131,17 @@ func shouldBeIgnored() { json.Marshal(nil) // nil argument, see issue #20. } -type WithInterface struct { - NoTag string -} - -func (w WithInterface) MarshalJSON() ([]byte, error) { - return json.Marshal(w.NoTag) -} - func nestedTypeWithInterface() { type Foo struct { - Nested WithInterface `json:"nested"` + Nested Marshaler `json:"nested"` } var foo Foo - json.Marshal(foo) // no error - json.Marshal(&foo) // no error - json.Marshal(Foo{}) // no error - json.Marshal(&Foo{}) // no error + json.Marshal(foo) + json.Marshal(&foo) + json.Marshal(Foo{}) + json.Marshal(&Foo{}) + json.Unmarshal(nil, &foo) + json.Unmarshal(nil, &Foo{}) } func ignoredNestedType() { @@ -159,10 +153,10 @@ func ignoredNestedType() { Exported string `json:"exported"` } var foo Foo - json.Marshal(foo) // no error - json.Marshal(&foo) // no error - json.Marshal(Foo{}) // no error - json.Marshal(&Foo{}) // no error + json.Marshal(foo) + json.Marshal(&foo) + json.Marshal(Foo{}) + json.Marshal(&Foo{}) } func ignoredNestedTypeWithSubsequentNoTagField() {