Skip to content

Commit ebf182c

Browse files
committed
reflect: avoid TypeOf in init
Calling TypeOf to initialize variables forces any import of "reflect" to link in the declared types of "reflect" even if they are unused. TypeOf operates on Type and which will pull in all transitive dependencies of Type, which includes Value as well. Avoid this problem by declaring a rtypeOf function that directly extracts the *rtype from an interface value without going through Type as an intermediate type. For a program that blank imports "reflect", this reduces the binary size by ~34 KiB. Updates #54097 Change-Id: I8dc7d8da8fedc48cc0dd842b69f510d17144827e Reviewed-on: https://go-review.googlesource.com/c/go/+/419757 Run-TryBot: Joseph Tsai <joetsai@digital-static.net> Reviewed-by: Bryan Mills <bcmills@google.com> Reviewed-by: Cherry Mui <cherryyz@google.com> TryBot-Result: Gopher Robot <gobot@golang.org>
1 parent 84be091 commit ebf182c

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

src/reflect/type.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1433,6 +1433,12 @@ func TypeOf(i any) Type {
14331433
return toType(eface.typ)
14341434
}
14351435

1436+
// rtypeOf directly extracts the *rtype of the provided value.
1437+
func rtypeOf(i any) *rtype {
1438+
eface := *(*emptyInterface)(unsafe.Pointer(&i))
1439+
return eface.typ
1440+
}
1441+
14361442
// ptrMap is the cache for PointerTo.
14371443
var ptrMap sync.Map // map[*rtype]*ptrType
14381444

src/reflect/value.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ func (v Value) panicNotBool() {
290290
v.mustBe(Bool)
291291
}
292292

293-
var bytesType = TypeOf(([]byte)(nil)).(*rtype)
293+
var bytesType = rtypeOf(([]byte)(nil))
294294

295295
// Bytes returns v's underlying value.
296296
// It panics if v's underlying value is not a slice of bytes or
@@ -1381,7 +1381,7 @@ func (v Value) Float() float64 {
13811381
panic(&ValueError{"reflect.Value.Float", v.kind()})
13821382
}
13831383

1384-
var uint8Type = TypeOf(uint8(0)).(*rtype)
1384+
var uint8Type = rtypeOf(uint8(0))
13851385

13861386
// Index returns v's i'th element.
13871387
// It panics if v's Kind is not Array, Slice, or String or i is out of range.
@@ -1640,7 +1640,7 @@ func (v Value) lenNonSlice() int {
16401640
panic(&ValueError{"reflect.Value.Len", v.kind()})
16411641
}
16421642

1643-
var stringType = TypeOf("").(*rtype)
1643+
var stringType = rtypeOf("")
16441644

16451645
// MapIndex returns the value associated with key in the map v.
16461646
// It panics if v's Kind is not Map.

0 commit comments

Comments
 (0)