Skip to content

Commit

Permalink
add OrElse method (#17)
Browse files Browse the repository at this point in the history
Co-authored-by: Luka Giorgadze <[email protected]>
  • Loading branch information
apatniv and LukaGiorgadze authored Jan 22, 2024
1 parent 032d23a commit 6c14e57
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions gonull.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ func (n Nullable[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(n.Val)
}

// OrElse returns the underlying Val if valid otherwise returns the provided defaultVal
func (n Nullable[T]) OrElse(defaultVal T) T {
if n.Valid {
return n.Val
} else {
return defaultVal
}
}

// zeroValue is a helper function that returns the zero value for the generic type T.
// It is used to set the zero value for the Val field of the Nullable struct when the value is nil.
func zeroValue[T any]() T {
Expand Down
9 changes: 9 additions & 0 deletions gonull_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,15 @@ func TestValuerAndScanner(t *testing.T) {
}, scannerNullableUnsupported)
}

func TestNullableOrElse(t *testing.T) {
value := "hello"
nonEmpty := NewNullable(value)
assert.Equal(t, value, nonEmpty.OrElse("world"))

var empty Nullable[string]
assert.Equal(t, "world", empty.OrElse("world"))
}

type customValuer struct {
value any
err error
Expand Down

0 comments on commit 6c14e57

Please sign in to comment.