From 9addd626c3026220d3ffddd2e508f9a4b7153bc4 Mon Sep 17 00:00:00 2001 From: Kaarel Raspel Date: Thu, 11 Mar 2021 00:00:54 +0200 Subject: [PATCH] Fixes #106 --- retrieve.go | 10 +++++++--- retrieve_test.go | 4 ++++ utils.go | 4 ++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/retrieve.go b/retrieve.go index acd7726..d600ba6 100644 --- a/retrieve.go +++ b/retrieve.go @@ -9,7 +9,7 @@ import ( func Get(out interface{}, path string) interface{} { result := get(reflect.ValueOf(out), path) - if result.Kind() != reflect.Invalid { + if result.Kind() != reflect.Invalid && !result.IsZero() { return result.Interface() } @@ -23,7 +23,11 @@ func get(value reflect.Value, path string) reflect.Value { length := value.Len() if length == 0 { - return resultSlice + zeroElement := reflect.Zero(value.Type().Elem()) + pathValue := get(zeroElement, path) + value = reflect.MakeSlice(reflect.SliceOf(pathValue.Type()), 0, 0) + + return value } for i := 0; i < length; i++ { @@ -31,7 +35,7 @@ func get(value reflect.Value, path string) reflect.Value { resultValue := get(item, path) - if resultValue.Kind() == reflect.Invalid { + if resultValue.Kind() == reflect.Invalid || resultValue.IsZero() { continue } diff --git a/retrieve_test.go b/retrieve_test.go index 05a3f22..b773296 100644 --- a/retrieve_test.go +++ b/retrieve_test.go @@ -12,6 +12,9 @@ func TestGetSlice(t *testing.T) { is.Equal(Get(SliceOf(foo), "ID"), []int{1}) is.Equal(Get(SliceOf(foo), "Bar.Name"), []string{"Test"}) is.Equal(Get(SliceOf(foo), "Bar"), []*Bar{bar}) + is.Equal(Get(([]Foo)(nil), "Bar.Name"), []string{}) + is.Equal(Get([]Foo{}, "Bar.Name"), []string{}) + is.Equal(Get([]*Foo{}, "Bar.Name"), []string{}) } func TestGetSliceMultiLevel(t *testing.T) { @@ -33,6 +36,7 @@ func TestGetNil(t *testing.T) { is.Equal(Get(foo2, "Bar.Name"), nil) is.Equal(Get([]*Foo{foo, foo2}, "Bar.Name"), []string{"Test"}) + is.Equal(Get([]*Foo{foo, foo2}, "Bar"), []*Bar{bar}) } func TestGetThroughInterface(t *testing.T) { diff --git a/utils.go b/utils.go index 2c80a16..43d9a2b 100644 --- a/utils.go +++ b/utils.go @@ -77,6 +77,10 @@ func redirectValue(value reflect.Value) reflect.Value { return value } + if !res.IsValid() && value.Kind() == reflect.Ptr { + return reflect.Zero(value.Type().Elem()) + } + value = res } }