Skip to content

Commit 9addd62

Browse files
committed
Fixes thoas#106
1 parent d02a012 commit 9addd62

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

retrieve.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import (
99
func Get(out interface{}, path string) interface{} {
1010
result := get(reflect.ValueOf(out), path)
1111

12-
if result.Kind() != reflect.Invalid {
12+
if result.Kind() != reflect.Invalid && !result.IsZero() {
1313
return result.Interface()
1414
}
1515

@@ -23,15 +23,19 @@ func get(value reflect.Value, path string) reflect.Value {
2323
length := value.Len()
2424

2525
if length == 0 {
26-
return resultSlice
26+
zeroElement := reflect.Zero(value.Type().Elem())
27+
pathValue := get(zeroElement, path)
28+
value = reflect.MakeSlice(reflect.SliceOf(pathValue.Type()), 0, 0)
29+
30+
return value
2731
}
2832

2933
for i := 0; i < length; i++ {
3034
item := value.Index(i)
3135

3236
resultValue := get(item, path)
3337

34-
if resultValue.Kind() == reflect.Invalid {
38+
if resultValue.Kind() == reflect.Invalid || resultValue.IsZero() {
3539
continue
3640
}
3741

retrieve_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ func TestGetSlice(t *testing.T) {
1212
is.Equal(Get(SliceOf(foo), "ID"), []int{1})
1313
is.Equal(Get(SliceOf(foo), "Bar.Name"), []string{"Test"})
1414
is.Equal(Get(SliceOf(foo), "Bar"), []*Bar{bar})
15+
is.Equal(Get(([]Foo)(nil), "Bar.Name"), []string{})
16+
is.Equal(Get([]Foo{}, "Bar.Name"), []string{})
17+
is.Equal(Get([]*Foo{}, "Bar.Name"), []string{})
1518
}
1619

1720
func TestGetSliceMultiLevel(t *testing.T) {
@@ -33,6 +36,7 @@ func TestGetNil(t *testing.T) {
3336

3437
is.Equal(Get(foo2, "Bar.Name"), nil)
3538
is.Equal(Get([]*Foo{foo, foo2}, "Bar.Name"), []string{"Test"})
39+
is.Equal(Get([]*Foo{foo, foo2}, "Bar"), []*Bar{bar})
3640
}
3741

3842
func TestGetThroughInterface(t *testing.T) {

utils.go

+4
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,10 @@ func redirectValue(value reflect.Value) reflect.Value {
7777
return value
7878
}
7979

80+
if !res.IsValid() && value.Kind() == reflect.Ptr {
81+
return reflect.Zero(value.Type().Elem())
82+
}
83+
8084
value = res
8185
}
8286
}

0 commit comments

Comments
 (0)