Skip to content

Commit

Permalink
ptr: add NonDefault
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Sep 4, 2024
1 parent 8e97257 commit ca3b3fe
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion ptr/ptr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit ca3b3fe

Please sign in to comment.