From 80959f822bf166e4eed51f819706fab7c856fe6f Mon Sep 17 00:00:00 2001 From: Muyao CHEN Date: Fri, 20 Sep 2024 20:19:49 +0200 Subject: [PATCH] waik: work with pointer --- walk/walk.go | 5 +++++ walk/walk_test.go | 24 +++++++++++++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/walk/walk.go b/walk/walk.go index 204e5ad..2bd10b5 100644 --- a/walk/walk.go +++ b/walk/walk.go @@ -6,6 +6,11 @@ import ( func Walk(x interface{}, fn func(string)) { val := reflect.ValueOf(x) + + if val.Kind() == reflect.Pointer { + val = val.Elem() // XXX: the object from the pointer + } + for i := 0; i < val.NumField(); i++ { field := val.Field(i) diff --git a/walk/walk_test.go b/walk/walk_test.go index c4c5d1c..b57178f 100644 --- a/walk/walk_test.go +++ b/walk/walk_test.go @@ -5,6 +5,14 @@ import ( "testing" ) +type Person struct { + Name string + Profile struct { + Age int + City string + } +} + func TestWalk(t *testing.T) { cases := []struct { Name string @@ -36,13 +44,15 @@ func TestWalk(t *testing.T) { }, { "nested fields", - struct { - Name string - Profile struct { - Age int - City string - } - }{"Chris", struct { + Person{"Chris", struct { + Age int + City string + }{29, "London"}}, + []string{"Chris", "London"}, + }, + { + "pointer to things", + &Person{"Chris", struct { Age int City string }{29, "London"}},