Skip to content

Commit 61672c9

Browse files
committed
reflect: add TypeFor
1 parent 3afa5da commit 61672c9

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

api/next/60088.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pkg reflect, func TypeFor[$0 interface{}]() Type

src/reflect/type.go

+5
Original file line numberDiff line numberDiff line change
@@ -2909,3 +2909,8 @@ func addTypeBits(bv *bitVector, offset uintptr, t *abi.Type) {
29092909
}
29102910
}
29112911
}
2912+
2913+
// TypeFor returns the reflection Type that represents the static type of T.
2914+
func TypeFor[T any]() Type {
2915+
return TypeOf((*T)(nil)).Elem()
2916+
}

src/reflect/type_test.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Copyright 2023 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package reflect_test
6+
7+
import (
8+
"reflect"
9+
"testing"
10+
)
11+
12+
func TestTypeFor(t *testing.T) {
13+
type (
14+
mystring string
15+
myiface interface{}
16+
)
17+
18+
testcases := []struct {
19+
wantFrom any
20+
got reflect.Type
21+
}{
22+
{new(int), reflect.TypeFor[int]()},
23+
{new(int64), reflect.TypeFor[int64]()},
24+
{new(string), reflect.TypeFor[string]()},
25+
{new(mystring), reflect.TypeFor[mystring]()},
26+
{new(any), reflect.TypeFor[any]()},
27+
{new(myiface), reflect.TypeFor[myiface]()},
28+
}
29+
for _, tc := range testcases {
30+
want := reflect.ValueOf(tc.wantFrom).Elem().Type()
31+
if want != tc.got {
32+
t.Errorf("unexpected reflect.Type: want %v; got %v", want, tc.got)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)