From fe19c87dd9cc7c5c8294c9aa6d04a37e5f0b897d Mon Sep 17 00:00:00 2001 From: Achilleas Koutsou Date: Mon, 17 Mar 2025 16:59:43 +0100 Subject: [PATCH] common: new utility function: DerefOrDefault() This is sort of the opposite of ToPtr(). It dereferences a pointer to its base value or returns the default value for the type if the pointer is nil. --- internal/common/pointers.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/internal/common/pointers.go b/internal/common/pointers.go index 58be2aab1..b262fb78d 100644 --- a/internal/common/pointers.go +++ b/internal/common/pointers.go @@ -3,3 +3,13 @@ package common func ToPtr[T any](x T) *T { return &x } + +// DerefOrDefault returns the dereferenced value of the given pointer or the +// default value for the type if unset. +func DerefOrDefault[T any](p *T) T { + var v T + if p != nil { + v = *p + } + return v +}