go-by-test/walk/walk.go

53 lines
936 B
Go
Raw Normal View History

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