walk: check if the field is of string type

This commit is contained in:
Muyao CHEN 2024-09-20 20:05:32 +02:00
parent 122770ae5c
commit 8026475424
2 changed files with 11 additions and 1 deletions

View File

@ -7,6 +7,8 @@ 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++ {
fn(val.Field(i).String()) if val.Field(i).Kind() == reflect.String {
fn(val.Field(i).String())
}
} }
} }

View File

@ -26,6 +26,14 @@ func TestWalk(t *testing.T) {
}{"Chris", "London"}, }{"Chris", "London"},
[]string{"Chris", "London"}, []string{"Chris", "London"},
}, },
{
"struct with non string field",
struct {
Name string
Age int
}{"Chris", 29},
[]string{"Chris"},
},
} }
for _, test := range cases { for _, test := range cases {