nest into struct for slice of pointer of struct

This commit is contained in:
Roy Lou 2016-07-27 08:05:16 +08:00
parent 14f46232cd
commit d12dfe1bb0
2 changed files with 32 additions and 1 deletions

View File

@ -558,7 +558,9 @@ func (s *Struct) nested(val reflect.Value) interface{} {
// TODO(arslan): should this be optional? // TODO(arslan): should this be optional?
// do not iterate of non struct types, just pass the value. Ie: []int, // do not iterate of non struct types, just pass the value. Ie: []int,
// []string, co... We only iterate further if it's a struct. // []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() finalVal = val.Interface()
break break
} }

View File

@ -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) { func TestMap_NestedSliceWithIntValues(t *testing.T) {
type person struct { type person struct {
Name string `structs:"name"` Name string `structs:"name"`