walk: reflect value of struct
This commit is contained in:
parent
3556c5b805
commit
b332088638
11
walk/walk.go
Normal file
11
walk/walk.go
Normal 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
27
walk/walk_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user