Skip to content

Commit

Permalink
Merge pull request #162 from ErfanMomeniii/master
Browse files Browse the repository at this point in the history
fix allow zero option problem in get func
  • Loading branch information
thoas committed Dec 26, 2022
2 parents 5573bc2 + b75b3f5 commit df86593
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
8 changes: 5 additions & 3 deletions retrieve.go
Expand Up @@ -9,7 +9,7 @@ import (
func Get(out interface{}, path string, opts ...option) interface{} {
options := newOptions(opts...)

result := get(reflect.ValueOf(out), path)
result := get(reflect.ValueOf(out), path, opts...)
// valid kind and we can return a result.Interface() without panic
if result.Kind() != reflect.Invalid && result.CanInterface() {
// if we don't allow zero and the result is a zero value return nil
Expand Down Expand Up @@ -38,7 +38,9 @@ func GetOrElse(v interface{}, def interface{}) interface{} {
return val.Elem().Interface()
}

func get(value reflect.Value, path string) reflect.Value {
func get(value reflect.Value, path string, opts ...option) reflect.Value {
options := newOptions(opts...)

if value.Kind() == reflect.Slice || value.Kind() == reflect.Array {
var resultSlice reflect.Value

Expand All @@ -57,7 +59,7 @@ func get(value reflect.Value, path string) reflect.Value {

resultValue := get(item, path)

if resultValue.Kind() == reflect.Invalid || resultValue.IsZero() {
if resultValue.Kind() == reflect.Invalid || (resultValue.IsZero() && !options.allowZero) {
continue
}

Expand Down
15 changes: 15 additions & 0 deletions retrieve_test.go
Expand Up @@ -67,6 +67,21 @@ func TestGetThroughInterface(t *testing.T) {
is.Equal(Get(foo, "BarPointer.Bars.Bar.Name"), []string{"Level2-1", "Level2-2"})
}

func TestGetWithAllowZero(t *testing.T) {
is := assert.New(t)

var test []struct {
Age int
}

for i := 0; i < 10; i++ {
test = append(test, struct{ Age int }{Age: i})
}

is.Equal(Get(test, "Age").([]int), []int{1, 2, 3, 4, 5, 6, 7, 8, 9})
is.Equal(Get(test, "Age", WithAllowZero()).([]int), []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
}

func TestGetNotFound(t *testing.T) {
is := assert.New(t)

Expand Down

0 comments on commit df86593

Please sign in to comment.