Skip to content

Commit

Permalink
Add PtrAsValue function to convert a pointer to a value
Browse files Browse the repository at this point in the history
  • Loading branch information
demdxx committed Jan 29, 2024
1 parent d920c7b commit a6978a9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
8 changes: 8 additions & 0 deletions logic.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,11 @@ func IfThen[T any](cond bool, a, b T) T {
}
return b
}

// PtrAsValue returns the value of `v` if `v` is not `nil`, else def
func PtrAsValue[T any](v *T, def T) T {
if v == nil {
return def
}
return *v
}
5 changes: 5 additions & 0 deletions logic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,9 @@ func TestLogic(t *testing.T) {
assert.Equal(t, 1, IfThen(true, 1, 2))
assert.Equal(t, 2, IfThen(false, 1, 2))
})

t.Run("PtrAsValue", func(t *testing.T) {
assert.Equal(t, 1, PtrAsValue(&[]int{1}[0], 2))
assert.Equal(t, 2, PtrAsValue((*int)(nil), 2))
})
}

0 comments on commit a6978a9

Please sign in to comment.