Skip to content

Commit

Permalink
Merge pull request #115 from vellotis/#106
Browse files Browse the repository at this point in the history
Fixes #106
  • Loading branch information
thoas committed Mar 11, 2021
2 parents 15dd68c + 9addd62 commit bb6cb22
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
10 changes: 7 additions & 3 deletions retrieve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand All @@ -23,15 +23,19 @@ 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++ {
item := value.Index(i)

resultValue := get(item, path)

if resultValue.Kind() == reflect.Invalid {
if resultValue.Kind() == reflect.Invalid || resultValue.IsZero() {
continue
}

Expand Down
4 changes: 4 additions & 0 deletions retrieve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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 TestGetMap(t *testing.T) {
Expand Down
4 changes: 4 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down

0 comments on commit bb6cb22

Please sign in to comment.