Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix allow zero option problem in get func #162

Merged
merged 2 commits into from Dec 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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