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

add OrElse method #17

Merged
merged 2 commits into from
Jan 22, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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