Skip to content

Commit

Permalink
Merge pull request #25 from m110/pointer-or-nil
Browse files Browse the repository at this point in the history
Option: Add PointerOrNil
  • Loading branch information
samber authored Sep 25, 2023
2 parents d606129 + 064ee78 commit fe4bf1d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
10 changes: 10 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,16 @@ func (o Option[T]) FlatMap(mapper func(value T) Option[T]) Option[T] {
return None[T]()
}

// PointerOrNil returns value if present or a nil pointer.
// Play: TODO
func (o Option[T]) PointerOrNil() *T {
if !o.isPresent {
return nil
}

return &o.value
}

// MarshalJSON encodes Option into json.
func (o Option[T]) MarshalJSON() ([]byte, error) {
if o.isPresent {
Expand Down
10 changes: 10 additions & 0 deletions option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,16 @@ func TestOptionOrEmpty(t *testing.T) {
is.Equal(0, None[int]().OrEmpty())
}

func TestOptionPointerOrNil(t *testing.T) {
is := assert.New(t)

p := Some(42).PointerOrNil()
is.NotNil(p)
is.Equal(42, *p)

is.Nil(None[int]().PointerOrNil())
}

func TestOptionForEach(t *testing.T) {
is := assert.New(t)

Expand Down

0 comments on commit fe4bf1d

Please sign in to comment.