diff --git a/option.go b/option.go index de023ed..ce11a4a 100644 --- a/option.go +++ b/option.go @@ -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 { diff --git a/option_test.go b/option_test.go index 0450047..d4b1f75 100644 --- a/option_test.go +++ b/option_test.go @@ -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)