Skip to content

Commit 42d2dfb

Browse files
earthboundkidgopherbot
authored andcommitted
reflect: add TypeFor
Fixes #60088 Change-Id: I7b43d329def22c2524501ba1d6bfc73becc823d1 GitHub-Last-Rev: becd714 GitHub-Pull-Request: #61598 Reviewed-on: https://go-review.googlesource.com/c/go/+/513478 TryBot-Result: Gopher Robot <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]> Reviewed-by: David Chase <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]>
1 parent f024e39 commit 42d2dfb

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

api/next/60088.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pkg reflect, func TypeFor[$0 interface{}]() Type #60088

src/reflect/type.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2911,3 +2911,8 @@ func addTypeBits(bv *bitVector, offset uintptr, t *abi.Type) {
29112911
}
29122912
}
29132913
}
2914+
2915+
// TypeFor returns the [Type] that represents the type argument T.
2916+
func TypeFor[T any]() Type {
2917+
return TypeOf((*T)(nil)).Elem()
2918+
}

src/reflect/type_test.go

Lines changed: 35 additions & 0 deletions
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: got %v; want %v", tc.got, want)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)