From e84fd344646e6ca35d17942d9cac399ad695318e Mon Sep 17 00:00:00 2001 From: esafonov Date: Sun, 3 Dec 2023 12:41:27 +0700 Subject: [PATCH] ptr.Coalesce --- ptr/ptr.go | 10 ++++++++++ ptr/ptr_test.go | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/ptr/ptr.go b/ptr/ptr.go index 409c596..052090c 100644 --- a/ptr/ptr.go +++ b/ptr/ptr.go @@ -106,3 +106,13 @@ func StrDef[T any](v *T, def string) string { } return fmt.Sprintf("%v", *v) } + +// Coalesce returns first not nil. If all elements are nil, nil will be returned. +func Coalesce[T any](pp ...*T) *T { + for _, p := range pp { + if p != nil { + return p + } + } + return nil +} diff --git a/ptr/ptr_test.go b/ptr/ptr_test.go index c057e9f..2d4a6c1 100644 --- a/ptr/ptr_test.go +++ b/ptr/ptr_test.go @@ -44,3 +44,18 @@ func ExampleEqual() { // true // false } + +func ExampleCoalesce() { + fmt.Println(Value(Coalesce[int](nil, Of(1), Of(2)))) + fmt.Println(Value(Coalesce[int](Of(2), Of(1), nil))) + fmt.Println(Value(Coalesce[int](Of(2)))) + fmt.Println(Coalesce[int](nil, nil)) + fmt.Println(Coalesce[int]()) + + // Output: + // 1 + // 2 + // 2 + // + // +}