From 82902877934be3638f4f74f038145a88de72e22b Mon Sep 17 00:00:00 2001 From: Corentin Clabaut <7072139+CorentinClabaut@users.noreply.github.com> Date: Sun, 24 Jul 2022 21:35:10 +0200 Subject: [PATCH] Add FromPtrOr (#177) --- README.md | 14 ++++++++++++++ type_manipulation.go | 9 +++++++++ type_manipulation_test.go | 17 +++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/README.md b/README.md index bc92360a..50997b8d 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,7 @@ Type manipulation helpers: - [ToPtr](#toptr) - [FromPtr](#fromptr) +- [FromPtrOr](#fromptror) - [ToSlicePtr](#tosliceptr) - [ToAnySlice](#toanyslice) - [FromAnySlice](#fromanyslice) @@ -1519,6 +1520,19 @@ value := lo.FromPtr[string](nil) // "" ``` +### FromPtrOr + +Returns the pointer value or the fallback value. + +```go +str := "hello world" +value := lo.FromPtrOr[string](&str, "empty") +// "hello world" + +value := lo.FromPtrOr[string](nil, "empty") +// "empty" +``` + ### ToSlicePtr Returns a slice of pointer copy of value. diff --git a/type_manipulation.go b/type_manipulation.go index 118609b2..fe99ee1f 100644 --- a/type_manipulation.go +++ b/type_manipulation.go @@ -14,6 +14,15 @@ func FromPtr[T any](x *T) T { return *x } +// FromPtrOr returns the pointer value or the fallback value. +func FromPtrOr[T any](x *T, fallback T) T { + if x == nil { + return fallback + } + + return *x +} + // ToSlicePtr returns a slice of pointer copy of value. func ToSlicePtr[T any](collection []T) []*T { return Map(collection, func(x T, _ int) *T { diff --git a/type_manipulation_test.go b/type_manipulation_test.go index 67dc94a6..c5553ed2 100644 --- a/type_manipulation_test.go +++ b/type_manipulation_test.go @@ -27,6 +27,23 @@ func TestFromPtr(t *testing.T) { is.EqualValues(ptr, FromPtr(&ptr)) } +func TestFromPtrOr(t *testing.T) { + is := assert.New(t) + + const fallbackStr = "fallback" + str := "foo" + ptrStr := &str + + const fallbackInt = -1 + i := 9 + ptrInt := &i + + is.Equal(str, FromPtrOr(ptrStr, fallbackStr)) + is.Equal(fallbackStr, FromPtrOr(nil, fallbackStr)) + is.Equal(i, FromPtrOr(ptrInt, fallbackInt)) + is.Equal(fallbackInt, FromPtrOr(nil, fallbackInt)) +} + func TestToSlicePtr(t *testing.T) { is := assert.New(t)