walk: reflect value of struct

This commit is contained in:
vinchent 2024-09-18 18:15:01 +02:00
parent 3556c5b805
commit b332088638
2 changed files with 38 additions and 0 deletions

11
walk/walk.go Normal file
View File

@ -0,0 +1,11 @@
package walk
import (
"reflect"
)
func Walk(x interface{}, fn func(string)) {
val := reflect.ValueOf(x)
field := val.Field(0)
fn(field.String())
}

27
walk/walk_test.go Normal file
View File

@ -0,0 +1,27 @@
package walk
import (
"testing"
)
func TestWalk(t *testing.T) {
t.Run("walk function test", func(t *testing.T) {
expected := "Chris"
var got []string
x := struct {
Name string
}{expected}
Walk(x, func(input string) {
got = append(got, input)
})
if len(got) != 1 {
t.Errorf("wrong number of function calls, got %d want %d", len(got), 1)
}
if got[0] != expected {
t.Errorf("got %q want %q", got[0], expected)
}
})
}