From 049c346e632c88aa43ec18c18f0b50b05a225c75 Mon Sep 17 00:00:00 2001 From: Muyao CHEN Date: Fri, 20 Sep 2024 20:27:53 +0200 Subject: [PATCH] walk: deal with slices --- walk/walk.go | 20 +++++++++++++++----- walk/walk_test.go | 28 ++++++++++++++++------------ 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/walk/walk.go b/walk/walk.go index 2bd10b5..923f223 100644 --- a/walk/walk.go +++ b/walk/walk.go @@ -5,15 +5,17 @@ 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 - } + val := getValue(x) for i := 0; i < val.NumField(); i++ { field := val.Field(i) + if val.Kind() == reflect.Slice { + for i := 0; i < val.Len(); i++ { + Walk(val.Index(i).Interface(), fn) + } + } + switch field.Kind() { case reflect.String: fn(field.String()) @@ -23,3 +25,11 @@ func Walk(x interface{}, fn func(string)) { } } } + +func getValue(x interface{}) reflect.Value { + val := reflect.ValueOf(x) + if val.Kind() == reflect.Pointer { + return val.Elem() + } + return val +} diff --git a/walk/walk_test.go b/walk/walk_test.go index b57178f..4f8439d 100644 --- a/walk/walk_test.go +++ b/walk/walk_test.go @@ -5,12 +5,14 @@ import ( "testing" ) +type Profile struct { + Age int + City string +} + type Person struct { Name string - Profile struct { - Age int - City string - } + Profile Profile } func TestWalk(t *testing.T) { @@ -44,20 +46,22 @@ func TestWalk(t *testing.T) { }, { "nested fields", - Person{"Chris", struct { - Age int - City string - }{29, "London"}}, + Person{"Chris", Profile{29, "London"}}, []string{"Chris", "London"}, }, { "pointer to things", - &Person{"Chris", struct { - Age int - City string - }{29, "London"}}, + &Person{"Chris", Profile{29, "London"}}, []string{"Chris", "London"}, }, + { + "slices", + []Profile{ + {29, "London"}, + {33, "Paris"}, + }, + []string{"London", "Paris"}, + }, } for _, test := range cases {