aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorCarl Johnson <me@carlmjohnson.net>2023-07-27 01:21:48 +0000
committerGopher Robot <gobot@golang.org>2023-07-31 15:50:15 +0000
commit42d2dfb4305aecb3a6e5494db6b8f6e48a09b420 (patch)
treeaeaf0439cb2f655fb583107f70ca10bb5159041e /src
parentf024e390bb0cb124487fd75f564ef8178ccba8f4 (diff)
downloadgo-42d2dfb4305aecb3a6e5494db6b8f6e48a09b420.tar.xz
reflect: add TypeFor
Fixes #60088 Change-Id: I7b43d329def22c2524501ba1d6bfc73becc823d1 GitHub-Last-Rev: becd714c4562da4a3280c3a56ebaf246e48e9f37 GitHub-Pull-Request: golang/go#61598 Reviewed-on: https://go-review.googlesource.com/c/go/+/513478 TryBot-Result: Gopher Robot <gobot@golang.org> Run-TryBot: Ian Lance Taylor <iant@golang.org> Auto-Submit: Ian Lance Taylor <iant@google.com> Reviewed-by: David Chase <drchase@google.com> Reviewed-by: Ian Lance Taylor <iant@google.com> Run-TryBot: Ian Lance Taylor <iant@google.com>
Diffstat (limited to 'src')
-rw-r--r--src/reflect/type.go5
-rw-r--r--src/reflect/type_test.go35
2 files changed, 40 insertions, 0 deletions
diff --git a/src/reflect/type.go b/src/reflect/type.go
index cefb9a43ab..c23b9973df 100644
--- a/src/reflect/type.go
+++ b/src/reflect/type.go
@@ -2911,3 +2911,8 @@ func addTypeBits(bv *bitVector, offset uintptr, t *abi.Type) {
}
}
}
+
+// TypeFor returns the [Type] that represents the type argument T.
+func TypeFor[T any]() Type {
+ return TypeOf((*T)(nil)).Elem()
+}
diff --git a/src/reflect/type_test.go b/src/reflect/type_test.go
new file mode 100644
index 0000000000..75784f9666
--- /dev/null
+++ b/src/reflect/type_test.go
@@ -0,0 +1,35 @@
+// Copyright 2023 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package reflect_test
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestTypeFor(t *testing.T) {
+ type (
+ mystring string
+ myiface interface{}
+ )
+
+ testcases := []struct {
+ wantFrom any
+ got reflect.Type
+ }{
+ {new(int), reflect.TypeFor[int]()},
+ {new(int64), reflect.TypeFor[int64]()},
+ {new(string), reflect.TypeFor[string]()},
+ {new(mystring), reflect.TypeFor[mystring]()},
+ {new(any), reflect.TypeFor[any]()},
+ {new(myiface), reflect.TypeFor[myiface]()},
+ }
+ for _, tc := range testcases {
+ want := reflect.ValueOf(tc.wantFrom).Elem().Type()
+ if want != tc.got {
+ t.Errorf("unexpected reflect.Type: got %v; want %v", tc.got, want)
+ }
+ }
+}