Skip to content

Commit

Permalink
Add CoalescePtr
Browse files Browse the repository at this point in the history
  • Loading branch information
Link512 committed Apr 18, 2024
1 parent 71d8341 commit ef3350e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,14 @@ func Coalesce[T comparable](v ...T) (result T, ok bool) {

return
}

// CoalescePtr returns the first non-nil argument or nil otherwise
func CoalescePtr[T any](v ...*T) *T {
for _, e := range v {
if e != nil {
return e
}
}

return nil
}
25 changes: 25 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,28 @@ func TestCoalesce(t *testing.T) {
is.Equal(result10, struct1)
is.True(ok10)
}

func TestCoalescePtr(t *testing.T) {
t.Parallel()
is := assert.New(t)

var (
one = 1
two = 2
three = 3
)

result1 := CoalescePtr[int]()
result2 := CoalescePtr(&one)
result3 := CoalescePtr(&one, nil, &two)
result4 := CoalescePtr(nil, &two, &three)
result5 := CoalescePtr[string](nil, nil, nil)
result6 := CoalescePtr(nil, nil, nil, &three)

is.Nil(result1)
is.Equal(&one, result2)
is.Equal(&one, result3)
is.Equal(&two, result4)
is.Nil(result5)
is.Equal(&three, result6)
}

0 comments on commit ef3350e

Please sign in to comment.