walk: refacto slice and struct

This commit is contained in:
Muyao CHEN 2024-09-20 20:36:24 +02:00
parent 1c3ad9b9d8
commit 799d730d14

View File

@ -7,18 +7,23 @@ import (
func Walk(x interface{}, fn func(string)) { func Walk(x interface{}, fn func(string)) {
val := getValue(x) val := getValue(x)
numberOfValues := 0
var getField func(int) reflect.Value
switch val.Kind() { switch val.Kind() {
case reflect.Struct:
for i := 0; i < val.NumField(); i++ {
// XXX: Interface() to get interface
Walk(val.Field(i).Interface(), fn)
}
case reflect.Slice:
for i := 0; i < val.Len(); i++ {
Walk(val.Index(i).Interface(), fn)
}
case reflect.String: case reflect.String:
fn(val.String()) fn(val.String())
case reflect.Struct:
numberOfValues = val.NumField()
getField = val.Field
case reflect.Slice:
numberOfValues = val.Len()
getField = val.Index
}
for i := 0; i < numberOfValues; i++ {
// XXX: Interface() to get interface
Walk(getField(i).Interface(), fn)
} }
} }