From 4b4576631e88df3b70117e3c6ffb3a40fb952287 Mon Sep 17 00:00:00 2001 From: Florian Forster Date: Wed, 27 Mar 2024 10:55:28 +0100 Subject: [PATCH] feat: Stop recursion at ignored fields. Fixes: #83 --- musttag.go | 8 +++++++- testdata/src/tests/tests.go | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/musttag.go b/musttag.go index 55edbfb..c147ec4 100644 --- a/musttag.go +++ b/musttag.go @@ -204,13 +204,19 @@ func (c *checker) checkStruct(styp *types.Struct, tag string) (valid bool) { continue } - if _, ok := reflect.StructTag(styp.Tag(i)).Lookup(tag); !ok { + tagValue, ok := reflect.StructTag(styp.Tag(i)).Lookup(tag) + if !ok { // tag is not required for embedded types; see issue #12. if !field.Embedded() { return false } } + // Do not recurse into ignored fields. + if tagValue == "-" { + return true + } + if valid := c.checkType(field.Type(), tag); !valid { return false } diff --git a/testdata/src/tests/tests.go b/testdata/src/tests/tests.go index 708b405..44266a8 100644 --- a/testdata/src/tests/tests.go +++ b/testdata/src/tests/tests.go @@ -149,3 +149,18 @@ func nestedTypeWithInterface() { json.Marshal(Foo{}) // no error json.Marshal(&Foo{}) // no error } + +func ignoredNestedType() { + type Nested struct { + NoTag string + } + type Foo struct { + Ignored Nested `json:"-"` + 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 +}