Skip to content

Commit

Permalink
Merge pull request #9 from moznion/feature/unwrap
Browse files Browse the repository at this point in the history
Support Option[T]#Unwrap() method
  • Loading branch information
moznion authored Jun 11, 2022
2 parents 762df1b + e8acc2f commit 45dd457
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
// <nil>
}

func ExampleOption_Take() {
some := Some[int](1)
v, err := some.Take()
Expand Down
7 changes: 7 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 45dd457

Please sign in to comment.