From dba7e48413995b50c0181fca8cca7d9d96fb3347 Mon Sep 17 00:00:00 2001 From: Momchil Atanasov Date: Sun, 10 Mar 2024 19:59:00 +0200 Subject: [PATCH] Add ValueOrDefault to optional type (#30) --- opt/value.go | 9 +++++++++ opt/value_test.go | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/opt/value.go b/opt/value.go index 130807b..ba57b45 100644 --- a/opt/value.go +++ b/opt/value.go @@ -10,6 +10,15 @@ type T[D any] struct { Value D } +// ValueOrDefault returns the value held in this optional if it is specified, +// otherwise it returns the given fallback value. +func (t T[D]) ValueOrDefault(fallback D) D { + if t.Specified { + return t.Value + } + return fallback +} + // ToPtr returns a pointer-based representation of the value held // in this optional. If this optional is not specified, then nil // is returned. diff --git a/opt/value_test.go b/opt/value_test.go index 1865e99..3308541 100644 --- a/opt/value_test.go +++ b/opt/value_test.go @@ -32,6 +32,13 @@ var _ = Describe("Optional", func() { Expect(v.Value).To(Equal(actual)) }) + It("is possible to get a fallback value", func() { + v := opt.Unspecified[string]() + Expect(v.ValueOrDefault("fallback")).To(Equal("fallback")) + v = opt.V("hello") + Expect(v.ValueOrDefault("fallback")).To(Equal("hello")) + }) + It("is possible to get a pointer representation of an unspecified value", func() { v := opt.Unspecified[string]() ptr := v.ToPtr()