-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpointer.go
58 lines (48 loc) · 953 Bytes
/
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
47
48
49
50
51
52
53
54
55
56
57
58
package ptr
import (
"fmt"
"reflect"
)
func String(s string) *string {
return &s
}
func Stringf(f string, a ...any) *string {
s := fmt.Sprintf(f, a...)
return &s
}
func Bool(b bool) *bool {
return &b
}
func Int64(i int64) *int64 {
return &i
}
func Int(i int) *int {
return &i
}
// DefaultOr get value of a pointer. If pointer is nil, zero value of this type will be return.
func DefaultOr[T any](i *T) T {
var v T
if i == nil {
return v
}
return *i
}
// DefaultOrElse get value of a pointer. If pointer is nil, or value will be return.
func DefaultOrElse[T any](i *T, or T) T {
if i == nil {
return or
}
return *i
}
// Ptr return a pointer of the value
func Ptr[T any](i T) *T {
return &i
}
// PtrOrNilForZero return a pointer of given not-zero value
// If given value is a zero value (reflect IsZero), nil will be return
func PtrOrNilForZero[T any](i T) *T {
if reflect.ValueOf(i).IsZero() {
return nil
}
return &i
}