walk: recursively search for string

This commit is contained in:
Muyao CHEN 2024-09-20 20:15:59 +02:00
parent 8026475424
commit 30a408c9e4
2 changed files with 22 additions and 2 deletions

View File

@ -7,8 +7,14 @@ import (
func Walk(x interface{}, fn func(string)) { func Walk(x interface{}, fn func(string)) {
val := reflect.ValueOf(x) val := reflect.ValueOf(x)
for i := 0; i < val.NumField(); i++ { for i := 0; i < val.NumField(); i++ {
if val.Field(i).Kind() == reflect.String { field := val.Field(i)
fn(val.Field(i).String())
switch field.Kind() {
case reflect.String:
fn(field.String())
case reflect.Struct:
// XXX: Interface() to get interface
Walk(field.Interface(), fn)
} }
} }
} }

View File

@ -34,6 +34,20 @@ func TestWalk(t *testing.T) {
}{"Chris", 29}, }{"Chris", 29},
[]string{"Chris"}, []string{"Chris"},
}, },
{
"nested fields",
struct {
Name string
Profile struct {
Age int
City string
}
}{"Chris", struct {
Age int
City string
}{29, "London"}},
[]string{"Chris", "London"},
},
} }
for _, test := range cases { for _, test := range cases {