Skip to content

Commit 94122c3

Browse files
authored
Merge pull request #2 from justinsb/lazy_init_type_discovery
Lazy-init types & packages
2 parents 4b7aa43 + e4eb82f commit 94122c3

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

type_map.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"reflect"
55
"runtime"
66
"strings"
7+
"sync"
78
"unsafe"
89
)
910

@@ -15,10 +16,17 @@ func typelinks1() [][]unsafe.Pointer
1516
//go:linkname typelinks2 reflect.typelinks
1617
func typelinks2() (sections []unsafe.Pointer, offset [][]int32)
1718

18-
var types = map[string]reflect.Type{}
19-
var packages = map[string]map[string]reflect.Type{}
19+
// initOnce guards initialization of types and packages
20+
var initOnce sync.Once
21+
22+
var types map[string]reflect.Type
23+
var packages map[string]map[string]reflect.Type
24+
25+
// discoverTypes initializes types and packages
26+
func discoverTypes() {
27+
types = make(map[string]reflect.Type)
28+
packages = make(map[string]map[string]reflect.Type)
2029

21-
func init() {
2230
ver := runtime.Version()
2331
if ver == "go1.5" || strings.HasPrefix(ver, "go1.5.") {
2432
loadGo15Types()
@@ -90,11 +98,13 @@ type emptyInterface struct {
9098

9199
// TypeByName return the type by its name, just like Class.forName in java
92100
func TypeByName(typeName string) Type {
101+
initOnce.Do(discoverTypes)
93102
return Type2(types[typeName])
94103
}
95104

96105
// TypeByPackageName return the type by its package and name
97106
func TypeByPackageName(pkgPath string, name string) Type {
107+
initOnce.Do(discoverTypes)
98108
pkgTypes := packages[pkgPath]
99109
if pkgTypes == nil {
100110
return nil

0 commit comments

Comments
 (0)