Skip to content

Commit a6b60d7

Browse files
authored
feat: skip explicitly ignored fields (#85)
1 parent f16d6ea commit a6b60d7

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

musttag.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -204,13 +204,19 @@ func (c *checker) checkStruct(styp *types.Struct, tag string) (valid bool) {
204204
continue
205205
}
206206

207-
if _, ok := reflect.StructTag(styp.Tag(i)).Lookup(tag); !ok {
207+
tagValue, ok := reflect.StructTag(styp.Tag(i)).Lookup(tag)
208+
if !ok {
208209
// tag is not required for embedded types; see issue #12.
209210
if !field.Embedded() {
210211
return false
211212
}
212213
}
213214

215+
// Do not recurse into ignored fields.
216+
if tagValue == "-" {
217+
return true
218+
}
219+
214220
if valid := c.checkType(field.Type(), tag); !valid {
215221
return false
216222
}

testdata/src/tests/tests.go

+15
Original file line numberDiff line numberDiff line change
@@ -149,3 +149,18 @@ func nestedTypeWithInterface() {
149149
json.Marshal(Foo{}) // no error
150150
json.Marshal(&Foo{}) // no error
151151
}
152+
153+
func ignoredNestedType() {
154+
type Nested struct {
155+
NoTag string
156+
}
157+
type Foo struct {
158+
Ignored Nested `json:"-"`
159+
Exported string `json:"exported"`
160+
}
161+
var foo Foo
162+
json.Marshal(foo) // no error
163+
json.Marshal(&foo) // no error
164+
json.Marshal(Foo{}) // no error
165+
json.Marshal(&Foo{}) // no error
166+
}

0 commit comments

Comments
 (0)