Skip to content

Commit

Permalink
feat: check whether structs within arrays/slices/maps implement a Mar…
Browse files Browse the repository at this point in the history
…shaler interface (#87)
  • Loading branch information
Adjective-Object committed Apr 5, 2024
1 parent a6b60d7 commit 4026f8f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
16 changes: 12 additions & 4 deletions musttag.go
Expand Up @@ -149,10 +149,6 @@ func (c *checker) checkType(typ types.Type, tag string) bool {
}
c.seenTypes[typ.String()] = struct{}{}

if implementsInterface(typ, c.ifaceWhitelist, c.imports) {
return true // the type implements a Marshaler interface; see issue #64.
}

styp, ok := c.parseStruct(typ)
if !ok {
return true // not a struct.
Expand All @@ -161,7 +157,19 @@ func (c *checker) checkType(typ types.Type, tag string) bool {
return c.checkStruct(styp, tag)
}

// recursively unwrap a type until we get to an underlying
// raw struct type that should have its fields checked
//
// SomeStruct -> struct{SomeStructField: ... }
// []*SomeStruct -> struct{SomeStructField: ... }
// ...
//
// exits early if it hits a type that implements a whitelisted interface
func (c *checker) parseStruct(typ types.Type) (*types.Struct, bool) {
if implementsInterface(typ, c.ifaceWhitelist, c.imports) {
return nil, false // the type implements a Marshaler interface; see issue #64.
}

switch typ := typ.(type) {
case *types.Pointer:
return c.parseStruct(typ.Elem())
Expand Down
11 changes: 11 additions & 0 deletions testdata/src/tests/tests.go
Expand Up @@ -164,3 +164,14 @@ func ignoredNestedType() {
json.Marshal(Foo{}) // no error
json.Marshal(&Foo{}) // no error
}

func interfaceSliceType() {
type WithMarshallableSlice struct {
List []Marshaler `json:"marshallable"`
}
var withMarshallableSlice WithMarshallableSlice

json.Marshal(withMarshallableSlice)
json.MarshalIndent(withMarshallableSlice, "", "")
json.NewEncoder(nil).Encode(withMarshallableSlice)
}

0 comments on commit 4026f8f

Please sign in to comment.