walk: loop on the string fields

This commit is contained in:
Muyao CHEN 2024-09-20 19:59:39 +02:00
parent 766d7449e8
commit 122770ae5c
2 changed files with 11 additions and 2 deletions

View File

@ -6,6 +6,7 @@ import (
func Walk(x interface{}, fn func(string)) { func Walk(x interface{}, fn func(string)) {
val := reflect.ValueOf(x) val := reflect.ValueOf(x)
field := val.Field(0) for i := 0; i < val.NumField(); i++ {
fn(field.String()) fn(val.Field(i).String())
}
} }

View File

@ -18,6 +18,14 @@ func TestWalk(t *testing.T) {
}{"Chris"}, }{"Chris"},
[]string{"Chris"}, []string{"Chris"},
}, },
{
"struct with two string fields",
struct {
Name string
City string
}{"Chris", "London"},
[]string{"Chris", "London"},
},
} }
for _, test := range cases { for _, test := range cases {