From fa8cc1d3f4dcd2af4b2abc0ca289c9761bd80b55 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 6 Nov 2020 21:21:09 +0800 Subject: [PATCH] improve gutil.Keys --- util/gutil/gutil.go | 6 ++++++ util/gutil/gutil_z_unit_test.go | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/util/gutil/gutil.go b/util/gutil/gutil.go index dd7cd4c62..5ea65c127 100644 --- a/util/gutil/gutil.go +++ b/util/gutil/gutil.go @@ -62,6 +62,12 @@ func Keys(mapOrStruct interface{}) (keysOrAttrs []string) { reflectValue = reflect.ValueOf(mapOrStruct) reflectKind = reflectValue.Kind() ) + if reflectKind == reflect.Ptr { + if !reflectValue.IsValid() || reflectValue.IsNil() { + reflectValue = reflect.New(reflectValue.Type().Elem()).Elem() + reflectKind = reflectValue.Kind() + } + } for reflectKind == reflect.Ptr { reflectValue = reflectValue.Elem() reflectKind = reflectValue.Kind() diff --git a/util/gutil/gutil_z_unit_test.go b/util/gutil/gutil_z_unit_test.go index 783c7e2e8..20d1f91fd 100755 --- a/util/gutil/gutil_z_unit_test.go +++ b/util/gutil/gutil_z_unit_test.go @@ -82,6 +82,16 @@ func Test_Keys(t *testing.T) { keys := gutil.Keys(new(T)) t.Assert(keys, g.SliceStr{"A", "B"}) }) + + gtest.C(t, func(t *gtest.T) { + type T struct { + A string + B int + } + var pointer *T + keys := gutil.Keys(pointer) + t.Assert(keys, g.SliceStr{"A", "B"}) + }) } func Test_Values(t *testing.T) {