-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreflect.go
More file actions
62 lines (55 loc) · 1.14 KB
/
reflect.go
File metadata and controls
62 lines (55 loc) · 1.14 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
package tools
import (
"errors"
"reflect"
)
var (
ByteSliceType = reflect.TypeOf([]byte{})
StringType = reflect.TypeOf("")
StringSliceType = reflect.TypeOf([]string{})
Int64Type = reflect.TypeOf(int64(0))
Int64SliceType = reflect.TypeOf([]int64{})
)
func IsByteSlice(typ reflect.Type) bool {
if typ.Kind() != reflect.Slice {
return false
}
return typ.Elem().Kind() == reflect.Uint8
}
func SetByteSliceValue(val reflect.Value, bs []byte) error {
if len(bs) > val.Cap() {
if !val.CanSet() {
return errors.New("tools: byte slice value cannot set")
}
val.Set(reflect.MakeSlice(val.Type(), len(bs), len(bs)))
} else {
val.SetLen(len(bs))
}
reflect.Copy(val, reflect.ValueOf(bs))
return nil
}
func IsDefaultZero[T any](t T) bool {
val := reflect.ValueOf(t)
if !val.IsValid() {
return true
}
return val.IsZero()
}
func IndirectType(typ reflect.Type) reflect.Type {
for {
if typ.Kind() == reflect.Pointer {
typ = typ.Elem()
} else {
return typ
}
}
}
func IndirectValue(val reflect.Value) reflect.Value {
for {
if val.Kind() == reflect.Pointer {
val = val.Elem()
} else {
return val
}
}
}