-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
pointer.go
46 lines (40 loc) · 1.03 KB
/
pointer.go
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
41
42
43
44
45
46
// Package pointer provides helper functions related to Go pointers.
package pointer
import (
"golang.org/x/exp/constraints"
)
// Primitive represents basic types that are safe to do basic comparisons by
// pointer dereference (checking nullity first).
type Primitive interface {
constraints.Ordered | bool
}
// Of returns a pointer to a.
func Of[A any](a A) *A {
return &a
}
// Copy returns a new pointer to a.
func Copy[A any](a *A) *A {
if a == nil {
return nil
}
na := *a
return &na
}
// Merge will return Copy(next) if next is not nil, otherwise return Copy(previous).
func Merge[P Primitive](previous, next *P) *P {
if next != nil {
return Copy(next)
}
return Copy(previous)
}
// Eq returns whether a and b are equal in underlying value.
//
// May only be used on pointers to primitive types, where the comparison is
// guaranteed to be sensible. For complex types (i.e. structs) consider implementing
// an Equals method.
func Eq[P Primitive](a, b *P) bool {
if a == nil || b == nil {
return a == b
}
return *a == *b
}