From ca3b3fe376c26f5120707df237779699d2df2cae Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Wed, 4 Sep 2024 20:35:17 +0300 Subject: [PATCH] ptr: add NonDefault --- ptr/ptr.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/ptr/ptr.go b/ptr/ptr.go index b8a337e..b04fa19 100644 --- a/ptr/ptr.go +++ b/ptr/ptr.go @@ -6,6 +6,7 @@ package ptr +// Clone creates a shallow copy of the given pointer. func Clone[T any](val *T) *T { if val == nil { return nil @@ -14,18 +15,26 @@ func Clone[T any](val *T) *T { return &valCopy } +// Ptr returns a pointer to the given value. func Ptr[T any](val T) *T { return &val } +// NonZero returns a pointer to the given comparable value, unless the value is the type's zero value. func NonZero[T comparable](val T) *T { var zero T - if val == zero { + return NonDefault(val, zero) +} + +// NonDefault returns a pointer to the first parameter, unless it is equal to the second parameter. +func NonDefault[T comparable](val, def T) *T { + if val == def { return nil } return &val } +// Val returns the value of the given pointer, or the zero value of the type if the pointer is nil. func Val[T any](ptr *T) (val T) { if ptr != nil { val = *ptr