Skip to content

Commit

Permalink
Merge pull request #10 from manicar2093/feat/identify-empty-slices
Browse files Browse the repository at this point in the history
feat: add identify empty slices
  • Loading branch information
manicar2093 authored Apr 17, 2024
2 parents f712949 + 0f0fd95 commit b5b0921
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
11 changes: 8 additions & 3 deletions goption.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func (c Optional[T]) Get() (T, error) {
return c.value, nil
}

// IsPresent returns true if there is a value present, otherwise false.
// IsPresent returns true if there is a value present, otherwise false. It recognizes an empty slice as not present so it returns false
func (c Optional[T]) IsPresent() bool {
return c.isValidValue
}
Expand Down Expand Up @@ -69,8 +69,13 @@ func isValidData[T any](value T) bool {
}
kind := typeOfValue.Kind()
val := reflect.ValueOf(value)
if kind == reflect.Pointer {

switch kind {
case reflect.Pointer:
return !val.IsNil()
case reflect.Slice:
return val.Len() != 0
default:
return !val.IsZero()
}
return !val.IsZero()
}
2 changes: 2 additions & 0 deletions goption_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ var _ = Describe("Goption", func() {
Entry("empty int", int(0), false),
Entry("filled int", int(1), true),
Entry("empty optional", goption.Optional[string]{}, false),
Entry("empty slice", []string{}, false),
Entry("empty slice of pointers", []*string{}, false),
)
})

Expand Down

0 comments on commit b5b0921

Please sign in to comment.