-
Notifications
You must be signed in to change notification settings - Fork 0
/
type.go
77 lines (69 loc) · 1.21 KB
/
type.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package x
import (
"reflect"
)
type (
//Type represents a type
Type struct {
Type reflect.Type
PkgPath string
Location string
Name string
Definition string
Scn int
Force bool
key string
}
)
// IsNamed returns true if type is named
func (t *Type) IsNamed() bool {
typ := t.Type
typ = SimpleType(typ)
return typ.Name() != ""
}
// SimpleType returns a simple type, it unwraps pointer, slice, array, and chan
func SimpleType(typ reflect.Type) reflect.Type {
switch typ.Kind() {
case reflect.Ptr, reflect.Slice, reflect.Array, reflect.Chan:
return SimpleType(typ.Elem())
default:
return typ
}
}
// NewType creates a type
func NewType(t reflect.Type, options ...Option) *Type {
typ := &Type{
Type: t,
}
for _, opt := range options {
opt(typ)
}
typ.init()
return typ
}
func (t *Type) init() {
if t.PkgPath == "" {
t.PkgPath = t.Type.PkgPath()
}
if t.Name == "" {
t.Name = t.Type.Name()
}
if t.Name == "" {
t.Name = t.Type.String()
}
}
func (t *Type) Key() string {
if t.key != "" {
return t.key
}
t.key = key(t)
return t.key
}
func key(t *Type) string {
pkg := t.PkgPath
name := t.Name
if pkg == "" {
return name
}
return pkg + "." + name
}