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.
This commit is contained in:
Achilleas Koutsou 2025-03-17 16:59:43 +01:00 committed by Sanne Raymaekers
parent 1a65e573eb
commit fe19c87dd9

View file

@ -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
}