From 3ea787e0a76ddb16ec1ac26dbb9d3aa0e9e3a510 Mon Sep 17 00:00:00 2001 From: Lukas Zapletal Date: Thu, 20 Mar 2025 11:58:42 +0100 Subject: [PATCH] feat: new method for fetching ignoring error --- nullable.go | 10 +++++++++- nullable_example_test.go | 8 ++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/nullable.go b/nullable.go index d2e3238..0830c43 100644 --- a/nullable.go +++ b/nullable.go @@ -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]) Dig() 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 { diff --git a/nullable_example_test.go b/nullable_example_test.go index c391817..54eba55 100644 --- a/nullable_example_test.go +++ b/nullable_example_test.go @@ -252,6 +252,7 @@ func ExampleNullable_unmarshalRequired() { return } fmt.Printf("obj.Name.Get(): %#v \n", val) + fmt.Printf("obj.Name.Dig(): %#v\n", obj.Name.Dig()) fmt.Printf("obj.Name.MustGet(): %#v\n", obj.Name.MustGet()) fmt.Println("---") @@ -275,6 +276,7 @@ func ExampleNullable_unmarshalRequired() { return } fmt.Printf("obj.Name.Get(): %#v \n", val) + fmt.Printf("obj.Name.Dig(): %#v\n", obj.Name.Dig()) fmt.Printf("obj.Name.MustGet(): %#v\n", obj.Name.MustGet()) fmt.Println("---") @@ -291,12 +293,14 @@ func ExampleNullable_unmarshalRequired() { // obj.Name.IsSpecified(): true // obj.Name.IsNull(): false // obj.Name.Get(): "" + // obj.Name.Dig(): "" // obj.Name.MustGet(): "" // --- // Value: // obj.Name.IsSpecified(): true // obj.Name.IsNull(): false // obj.Name.Get(): "foo" + // obj.Name.Dig(): "foo" // obj.Name.MustGet(): "foo" // --- } @@ -355,6 +359,7 @@ func ExampleNullable_unmarshalOptional() { return } fmt.Printf("obj.Name.Get(): %#v \n", val) + fmt.Printf("obj.Name.Dig(): %#v\n", obj.Name.Dig()) fmt.Printf("obj.Name.MustGet(): %#v\n", obj.Name.MustGet()) fmt.Println("---") @@ -378,6 +383,7 @@ func ExampleNullable_unmarshalOptional() { return } fmt.Printf("obj.Name.Get(): %#v \n", val) + fmt.Printf("obj.Name.Dig(): %#v\n", obj.Name.Dig()) fmt.Printf("obj.Name.MustGet(): %#v\n", obj.Name.MustGet()) fmt.Println("---") @@ -394,12 +400,14 @@ func ExampleNullable_unmarshalOptional() { // obj.Name.IsSpecified(): true // obj.Name.IsNull(): false // obj.Name.Get(): "" + // obj.Name.Dig(): "" // obj.Name.MustGet(): "" // --- // Value: // obj.Name.IsSpecified(): true // obj.Name.IsNull(): false // obj.Name.Get(): "foo" + // obj.Name.Dig(): "foo" // obj.Name.MustGet(): "foo" // --- }