go-by-test/walk/walk.go

53 lines
936 B
Go
Raw Normal View History

2024-09-18 16:15:01 +00:00
package walk
import (
"reflect"
)
func Walk(x interface{}, fn func(string)) {
2024-09-20 18:27:53 +00:00
val := getValue(x)
2024-09-20 18:19:49 +00:00
2024-09-20 18:44:40 +00:00
walkValue := func(value reflect.Value) {
Walk(value.Interface(), fn)
}
2024-09-20 18:36:24 +00:00
2024-09-20 18:32:37 +00:00
switch val.Kind() {
case reflect.String:
fn(val.String())
2024-09-20 18:36:24 +00:00
case reflect.Struct:
2024-09-20 18:44:40 +00:00
for i := 0; i < val.NumField(); i++ {
// XXX: Interface() to get interface
walkValue(val.Field(i))
}
2024-09-20 18:37:54 +00:00
case reflect.Slice, reflect.Array:
2024-09-20 18:44:40 +00:00
for i := 0; i < val.Len(); i++ {
walkValue(val.Index(i))
}
2024-09-20 18:41:50 +00:00
case reflect.Map:
for _, key := range val.MapKeys() {
2024-09-20 18:44:40 +00:00
walkValue(val.MapIndex(key))
2024-09-20 18:41:50 +00:00
}
2024-09-20 19:00:47 +00:00
case reflect.Chan:
for {
if v, ok := val.Recv(); ok {
walkValue(v)
} else {
break
}
}
2024-09-20 19:04:25 +00:00
case reflect.Func:
valFnResult := val.Call(nil)
for _, res := range valFnResult {
walkValue(res)
}
2024-09-20 18:36:24 +00:00
}
2024-09-18 16:15:01 +00:00
}
2024-09-20 18:27:53 +00:00
func getValue(x interface{}) reflect.Value {
val := reflect.ValueOf(x)
if val.Kind() == reflect.Pointer {
return val.Elem()
}
return val
}