walk: recursively search for string
This commit is contained in:
parent
8026475424
commit
30a408c9e4
10
walk/walk.go
10
walk/walk.go
@ -7,8 +7,14 @@ import (
|
||||
func Walk(x interface{}, fn func(string)) {
|
||||
val := reflect.ValueOf(x)
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
if val.Field(i).Kind() == reflect.String {
|
||||
fn(val.Field(i).String())
|
||||
field := val.Field(i)
|
||||
|
||||
switch field.Kind() {
|
||||
case reflect.String:
|
||||
fn(field.String())
|
||||
case reflect.Struct:
|
||||
// XXX: Interface() to get interface
|
||||
Walk(field.Interface(), fn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -34,6 +34,20 @@ func TestWalk(t *testing.T) {
|
||||
}{"Chris", 29},
|
||||
[]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 {
|
||||
|
Loading…
Reference in New Issue
Block a user