From 799d730d14ae8c78db01116e81c2605cb3c5b7a7 Mon Sep 17 00:00:00 2001 From: Muyao CHEN Date: Fri, 20 Sep 2024 20:36:24 +0200 Subject: [PATCH] walk: refacto slice and struct --- walk/walk.go | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/walk/walk.go b/walk/walk.go index 10777d7..d6e80ed 100644 --- a/walk/walk.go +++ b/walk/walk.go @@ -7,18 +7,23 @@ import ( func Walk(x interface{}, fn func(string)) { val := getValue(x) + numberOfValues := 0 + var getField func(int) reflect.Value + switch val.Kind() { - case reflect.Struct: - for i := 0; i < val.NumField(); i++ { - // XXX: Interface() to get interface - Walk(val.Field(i).Interface(), fn) - } - case reflect.Slice: - for i := 0; i < val.Len(); i++ { - Walk(val.Index(i).Interface(), fn) - } case reflect.String: fn(val.String()) + case reflect.Struct: + numberOfValues = val.NumField() + getField = val.Field + case reflect.Slice: + numberOfValues = val.Len() + getField = val.Index + } + + for i := 0; i < numberOfValues; i++ { + // XXX: Interface() to get interface + Walk(getField(i).Interface(), fn) } }