forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathptr.go
More file actions
40 lines (33 loc) · 798 Bytes
/
ptr.go
File metadata and controls
40 lines (33 loc) · 798 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Package ptr contains some utility methods related to pointers.
package ptr
import "golang.org/x/exp/constraints"
type number interface {
constraints.Integer | constraints.Float
}
// Ref returns a reference to v.
func Ref[T any](v T) *T {
return &v
}
// NilOrEmpty returns true if s is nil or the empty string.
func NilOrEmpty(s *string) bool {
return s == nil || *s == ""
}
// NilToEmpty coalesces a nil value to the empty value.
func NilToEmpty[T any](s *T) T {
var def T
if s == nil {
return def
}
return *s
}
// NilToDefault coalesces a nil value to the provided default value.
func NilToDefault[T any](s *T, def T) T {
if s == nil {
return def
}
return *s
}
// NilOrZero returns true if v is nil or 0.
func NilOrZero[T number](v *T) bool {
return v == nil || *v == 0
}