Skip to content

Commit

Permalink
Support UnwrapAsPtr() method to unwrap the Option value as a pointer
Browse files Browse the repository at this point in the history
Fix #25

Signed-off-by: moznion <[email protected]>
  • Loading branch information
moznion committed Jul 14, 2023
1 parent 4ed01b5 commit b455687
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
20 changes: 20 additions & 0 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,26 @@ func ExampleOption_Unwrap() {
// <nil>
}

func ExampleOption_UnwrapAsPtr() {
fmt.Printf("%v\n", *Some[int](12345).UnwrapAsPtr())
fmt.Printf("%v\n", None[int]().UnwrapAsPtr())
fmt.Printf("%v\n", None[*int]().UnwrapAsPtr())

num := 123
fmt.Printf("%v\n", *FromNillable[int](&num).UnwrapAsPtr())
fmt.Printf("%v\n", FromNillable[int](nil).UnwrapAsPtr())
fmt.Printf("%v\n", **PtrFromNillable[int](&num).UnwrapAsPtr()) // NOTE: this dereferences tha unwrapped value
fmt.Printf("%v\n", PtrFromNillable[int](nil).UnwrapAsPtr())
// Output:
// 12345
// <nil>
// <nil>
// 123
// <nil>
// 123
// <nil>
}

func ExampleOption_Take() {
some := Some[int](1)
v, err := some.Take()
Expand Down
10 changes: 10 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,16 @@ func (o Option[T]) Unwrap() T {
return o[value]
}

// UnwrapAsPtr returns the contained value in receiver Option as a pointer.
// This is similar to `Unwrap()` method but the difference is this method returns a pointer value instead of the actual value.
// If the receiver Option value is None, this method returns nil.
func (o Option[T]) UnwrapAsPtr() *T {
if o.IsNone() {
return nil
}
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
15 changes: 15 additions & 0 deletions option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ func TestOption_Unwrap(t *testing.T) {
assert.Nil(t, PtrFromNillable[int](nil).Unwrap())
}

func TestOption_UnwrapAsPointer(t *testing.T) {
str := "foo"
refStr := &str
assert.EqualValues(t, &str, Some[string](str).UnwrapAsPtr())
assert.EqualValues(t, &refStr, Some[*string](refStr).UnwrapAsPtr())
assert.Nil(t, None[string]().UnwrapAsPtr())
assert.Nil(t, None[*string]().UnwrapAsPtr())

i := 123
assert.Equal(t, &i, FromNillable[int](&i).UnwrapAsPtr())
assert.Nil(t, FromNillable[int](nil).UnwrapAsPtr())
assert.Equal(t, &i, *PtrFromNillable[int](&i).UnwrapAsPtr())
assert.Nil(t, PtrFromNillable[int](nil).UnwrapAsPtr())
}

func TestOption_Take(t *testing.T) {
v, err := Some[int](123).Take()
assert.NoError(t, err)
Expand Down

0 comments on commit b455687

Please sign in to comment.