From e8acc2f9cd372ee00a56fd83395c816ac00931d7 Mon Sep 17 00:00:00 2001 From: moznion Date: Fri, 10 Jun 2022 22:17:30 -0700 Subject: [PATCH] Support Option[T]#Unwrap() method Signed-off-by: moznion --- examples_test.go | 10 ++++++++++ option.go | 7 +++++++ option_test.go | 6 ++++++ 3 files changed, 23 insertions(+) diff --git a/examples_test.go b/examples_test.go index 0ff0bb3..476b24b 100644 --- a/examples_test.go +++ b/examples_test.go @@ -25,6 +25,16 @@ func ExampleOption_IsSome() { // false } +func ExampleOption_Unwrap() { + fmt.Printf("%v\n", Some[int](12345).Unwrap()) + fmt.Printf("%v\n", None[int]().Unwrap()) + fmt.Printf("%v\n", None[*int]().Unwrap()) + // Output: + // 12345 + // 0 + // +} + func ExampleOption_Take() { some := Some[int](1) v, err := some.Take() diff --git a/option.go b/option.go index 7c1c676..97a885d 100644 --- a/option.go +++ b/option.go @@ -36,6 +36,13 @@ func (o Option[T]) IsSome() bool { return o.exists != nil } +// Unwrap returns the value regardless of Some/None status. +// If the Option value is Some, this method returns the actual value. +// On the other hand, if the Option value is None, this method returns the *default* value according to the type. +func (o Option[T]) Unwrap() T { + return o.value +} + // Take takes the contained value in Option. // If Option value is Some, this returns the value that is contained in Option. // On the other hand, this returns an ErrNoneValueTaken as the second return value. diff --git a/option_test.go b/option_test.go index cdbe50d..0de9ebf 100644 --- a/option_test.go +++ b/option_test.go @@ -18,6 +18,12 @@ func TestOption_IsSome(t *testing.T) { assert.True(t, Some[int](123).IsSome()) } +func TestOption_Unwrap(t *testing.T) { + assert.Equal(t, "foo", Some[string]("foo").Unwrap()) + assert.Equal(t, "", None[string]().Unwrap()) + assert.Nil(t, None[*string]().Unwrap()) +} + func TestOption_Take(t *testing.T) { v, err := Some[int](123).Take() assert.NoError(t, err)