walk: rerefacto

This commit is contained in:
Muyao CHEN 2024-09-20 20:44:40 +02:00
parent 61a0d0ff03
commit 10a93aeb27

View File

@ -7,28 +7,27 @@ import (
func Walk(x interface{}, fn func(string)) { func Walk(x interface{}, fn func(string)) {
val := getValue(x) val := getValue(x)
numberOfValues := 0 walkValue := func(value reflect.Value) {
var getField func(int) reflect.Value Walk(value.Interface(), fn)
}
switch val.Kind() { switch val.Kind() {
case reflect.String: case reflect.String:
fn(val.String()) fn(val.String())
case reflect.Struct: case reflect.Struct:
numberOfValues = val.NumField() for i := 0; i < val.NumField(); i++ {
getField = val.Field // XXX: Interface() to get interface
walkValue(val.Field(i))
}
case reflect.Slice, reflect.Array: case reflect.Slice, reflect.Array:
numberOfValues = val.Len() for i := 0; i < val.Len(); i++ {
getField = val.Index walkValue(val.Index(i))
}
case reflect.Map: case reflect.Map:
for _, key := range val.MapKeys() { for _, key := range val.MapKeys() {
Walk(val.MapIndex(key).Interface(), fn) walkValue(val.MapIndex(key))
} }
} }
for i := 0; i < numberOfValues; i++ {
// XXX: Interface() to get interface
Walk(getField(i).Interface(), fn)
}
} }
func getValue(x interface{}) reflect.Value { func getValue(x interface{}) reflect.Value {