Skip to content
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
10 changes: 9 additions & 1 deletion nullable.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,15 @@ func (t Nullable[T]) Get() (T, error) {
return t[true], nil
}

// MustGet retrieves the underlying value, if present, and panics if the value was not present
// Dig retrieves the underlying value or returns empty value if not present or was `null`. Use Get to distinguish between these cases.
func (t Nullable[T]) GetOrEmpty() T {
var empty T
if !t.IsSpecified() || t.IsNull() {
return empty
}
return t[true]
}

func (t Nullable[T]) MustGet() T {
v, err := t.Get()
if err != nil {
Expand Down
8 changes: 8 additions & 0 deletions nullable_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ func ExampleNullable_unmarshalRequired() {
return
}
fmt.Printf("obj.Name.Get(): %#v <nil>\n", val)
fmt.Printf("obj.Name.GetOrEmpty(): %#v\n", obj.Name.GetOrEmpty())
fmt.Printf("obj.Name.MustGet(): %#v\n", obj.Name.MustGet())
fmt.Println("---")

Expand All @@ -275,6 +276,7 @@ func ExampleNullable_unmarshalRequired() {
return
}
fmt.Printf("obj.Name.Get(): %#v <nil>\n", val)
fmt.Printf("obj.Name.GetOrEmpty(): %#v\n", obj.Name.GetOrEmpty())
fmt.Printf("obj.Name.MustGet(): %#v\n", obj.Name.MustGet())
fmt.Println("---")

Expand All @@ -291,12 +293,14 @@ func ExampleNullable_unmarshalRequired() {
// obj.Name.IsSpecified(): true
// obj.Name.IsNull(): false
// obj.Name.Get(): "" <nil>
// obj.Name.GetOrEmpty(): ""
// obj.Name.MustGet(): ""
// ---
// Value:
// obj.Name.IsSpecified(): true
// obj.Name.IsNull(): false
// obj.Name.Get(): "foo" <nil>
// obj.Name.GetOrEmpty(): "foo"
// obj.Name.MustGet(): "foo"
// ---
}
Expand Down Expand Up @@ -355,6 +359,7 @@ func ExampleNullable_unmarshalOptional() {
return
}
fmt.Printf("obj.Name.Get(): %#v <nil>\n", val)
fmt.Printf("obj.Name.GetOrEmpty(): %#v\n", obj.Name.GetOrEmpty())
fmt.Printf("obj.Name.MustGet(): %#v\n", obj.Name.MustGet())
fmt.Println("---")

Expand All @@ -378,6 +383,7 @@ func ExampleNullable_unmarshalOptional() {
return
}
fmt.Printf("obj.Name.Get(): %#v <nil>\n", val)
fmt.Printf("obj.Name.GetOrEmpty(): %#v\n", obj.Name.GetOrEmpty())
fmt.Printf("obj.Name.MustGet(): %#v\n", obj.Name.MustGet())
fmt.Println("---")

Expand All @@ -394,12 +400,14 @@ func ExampleNullable_unmarshalOptional() {
// obj.Name.IsSpecified(): true
// obj.Name.IsNull(): false
// obj.Name.Get(): "" <nil>
// obj.Name.GetOrEmpty(): ""
// obj.Name.MustGet(): ""
// ---
// Value:
// obj.Name.IsSpecified(): true
// obj.Name.IsNull(): false
// obj.Name.Get(): "foo" <nil>
// obj.Name.GetOrEmpty(): "foo"
// obj.Name.MustGet(): "foo"
// ---
}
Loading