Skip to content

Commit

Permalink
nest into struct for slice of pointer of struct
Browse files Browse the repository at this point in the history
  • Loading branch information
roylou committed Jul 27, 2016
1 parent 14f4623 commit d12dfe1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
4 changes: 3 additions & 1 deletion structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,9 @@ func (s *Struct) nested(val reflect.Value) interface{} {
// TODO(arslan): should this be optional?
// do not iterate of non struct types, just pass the value. Ie: []int,
// []string, co... We only iterate further if it's a struct.
if val.Type().Elem().Kind() != reflect.Struct {
if val.Type().Elem().Kind() != reflect.Struct &&
!(val.Type().Elem().Kind() == reflect.Ptr &&
val.Type().Elem().Elem().Kind() == reflect.Struct) {
finalVal = val.Interface()
break
}
Expand Down
29 changes: 29 additions & 0 deletions structs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,35 @@ func TestMap_NestedSliceWithStructValues(t *testing.T) {
}
}

func TestMap_NestedSliceWithPointerOfStructValues(t *testing.T) {
type address struct {
Country string `structs:"customCountryName"`
}

type person struct {
Name string `structs:"name"`
Addresses []*address `structs:"addresses"`
}

p := person{
Name: "test",
Addresses: []*address{
&address{Country: "England"},
&address{Country: "Italy"},
},
}
mp := Map(p)

mpAddresses := mp["addresses"].([]interface{})
if _, exists := mpAddresses[0].(map[string]interface{})["Country"]; exists {
t.Errorf("Expecting customCountryName, but found Country")
}

if _, exists := mpAddresses[0].(map[string]interface{})["customCountryName"]; !exists {
t.Errorf("customCountryName key not found")
}
}

func TestMap_NestedSliceWithIntValues(t *testing.T) {
type person struct {
Name string `structs:"name"`
Expand Down

0 comments on commit d12dfe1

Please sign in to comment.