Merge "propertyIndexesWithTag can handle slice of struct"

This commit is contained in:
Treehugger Robot 2021-02-24 00:54:56 +00:00 committed by Gerrit Code Review
commit 2910183696
3 changed files with 31 additions and 2 deletions

View file

@ -125,3 +125,7 @@ func isStructPtr(t reflect.Type) bool {
func isSlice(t reflect.Type) bool {
return t.Kind() == reflect.Slice
}
func isSliceOfStruct(t reflect.Type) bool {
return isSlice(t) && isStruct(t.Elem())
}

View file

@ -56,8 +56,8 @@ func propertyIndexesWithTag(t reflect.Type, key, value string) [][]int {
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
ft := field.Type
if isStruct(ft) || isStructPtr(ft) {
if ft.Kind() == reflect.Ptr {
if isStruct(ft) || isStructPtr(ft) || isSliceOfStruct(ft) {
if ft.Kind() == reflect.Ptr || ft.Kind() == reflect.Slice {
ft = ft.Elem()
}
subIndexes := propertyIndexesWithTag(ft, key, value)

View file

@ -155,6 +155,31 @@ func TestPropertyIndexesWithTag(t *testing.T) {
}{},
want: [][]int{{0, 0}},
},
{
name: "slice of struct",
ps: &struct {
Other int
Foo []struct {
Other int
Bar string `name:"value"`
}
}{},
want: [][]int{{1, 1}},
},
{
name: "slice^2 of struct",
ps: &struct {
Other int
Foo []struct {
Other int
Bar []struct {
Other int
Baz string `name:"value"`
}
}
}{},
want: [][]int{{1, 1, 1}},
},
{
name: "nil",
ps: (*struct {