From a6978a92beed1df3bcd4556c1cb71e3a9963726f Mon Sep 17 00:00:00 2001 From: Dmitry Ponomarev Date: Mon, 29 Jan 2024 17:13:36 +0100 Subject: [PATCH] Add `PtrAsValue` function to convert a pointer to a value --- logic.go | 8 ++++++++ logic_test.go | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/logic.go b/logic.go index 8bd862a..ef603d3 100644 --- a/logic.go +++ b/logic.go @@ -22,3 +22,11 @@ func IfThen[T any](cond bool, a, b T) T { } return b } + +// PtrAsValue returns the value of `v` if `v` is not `nil`, else def +func PtrAsValue[T any](v *T, def T) T { + if v == nil { + return def + } + return *v +} diff --git a/logic_test.go b/logic_test.go index 3ff23e6..c415176 100644 --- a/logic_test.go +++ b/logic_test.go @@ -34,4 +34,9 @@ func TestLogic(t *testing.T) { assert.Equal(t, 1, IfThen(true, 1, 2)) assert.Equal(t, 2, IfThen(false, 1, 2)) }) + + t.Run("PtrAsValue", func(t *testing.T) { + assert.Equal(t, 1, PtrAsValue(&[]int{1}[0], 2)) + assert.Equal(t, 2, PtrAsValue((*int)(nil), 2)) + }) }