Skip to content

Commit

Permalink
ptr.Coalesce
Browse files Browse the repository at this point in the history
  • Loading branch information
esafonov committed Dec 3, 2023
1 parent 2e1db3b commit e84fd34
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
10 changes: 10 additions & 0 deletions ptr/ptr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
15 changes: 15 additions & 0 deletions ptr/ptr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
// <nil>
// <nil>
}

0 comments on commit e84fd34

Please sign in to comment.