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)) {
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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 {
|
||||||
|
Loading…
Reference in New Issue
Block a user