From dd56fb230399cd78df661e53689f44e912089130 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=C5=82osz=20Sm=C3=B3=C5=82ka?= Date: Fri, 21 Apr 2023 11:40:22 +0200 Subject: [PATCH 1/2] Option: Add PointerOrNil --- option.go | 10 ++++++++++ option_test.go | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/option.go b/option.go index 3e8ef4f..ef516e5 100644 --- a/option.go +++ b/option.go @@ -172,6 +172,16 @@ func (o Option[T]) FlatMap(mapper func(value T) Option[T]) Option[T] { return None[T]() } +// OrNil 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 052cb4d..79f540b 100644 --- a/option_test.go +++ b/option_test.go @@ -115,6 +115,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) From 064ee78166986e50dbf43d53767eb647ea1b3935 Mon Sep 17 00:00:00 2001 From: Samuel Berthe Date: Mon, 25 Sep 2023 15:18:59 +0200 Subject: [PATCH 2/2] Update option.go --- option.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/option.go b/option.go index ef516e5..71d0e5e 100644 --- a/option.go +++ b/option.go @@ -172,7 +172,7 @@ func (o Option[T]) FlatMap(mapper func(value T) Option[T]) Option[T] { return None[T]() } -// OrNil returns value if present or a nil pointer. +// PointerOrNil returns value if present or a nil pointer. // Play: TODO func (o Option[T]) PointerOrNil() *T { if !o.isPresent {