-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtypeutil.go
More file actions
73 lines (59 loc) · 1.51 KB
/
typeutil.go
File metadata and controls
73 lines (59 loc) · 1.51 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Package typeutil contains a collection of type-related generic utility
functions.
This package provides a set of utility functions and definitions for working
with generic types in Go.
*/
package typeutil
import (
"reflect"
)
// IsNil returns true if the input value is nil.
func IsNil(v any) bool {
if v == nil {
return true
}
value := reflect.ValueOf(v)
switch value.Kind() { //nolint:exhaustive
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice, reflect.UnsafePointer:
return value.IsNil()
}
return false
}
// IsZero returns true if the input value is equal to the zero instance (e.g. empty string, 0 int, nil pointer).
func IsZero[T any](v T) bool {
return reflect.ValueOf(&v).Elem().IsZero()
}
// Zero returns the zero instance (e.g. empty string, 0 int, nil pointer).
func Zero[T any](_ T) T {
var zero T
return zero
}
// Pointer returns the address of v.
func Pointer[T any](v T) *T {
return &v
}
// Value returns the value of the provided pointer or the type default (zero value) if nil.
func Value[T any](p *T) T {
if IsNil(p) {
var zero T
return zero
}
return *p
}
// BoolToInt converts a boolean value to an integer.
//
// NOTE: this is currently the fastest implementation as it will be optimized by
// the compiler with a MOVBLZX instruction.
// Ref.:
// - https://0x0f.me/blog/golang-compiler-optimization/
// - https://github.com/golang/go/issues/6011
func BoolToInt(b bool) int {
var i int
if b {
i = 1
} else {
i = 0
}
return i
}