diff options
author | Ayke van Laethem <[email protected]> | 2024-01-18 20:10:28 +0100 |
---|---|---|
committer | Ayke van Laethem <[email protected]> | 2024-01-19 13:46:27 +0100 |
commit | 204659bdcd71e7601f077c246a97176a3e88075f (patch) | |
tree | f544a7b56490d7b35f1d2ced4f233a3d72159c7b /src/reflect | |
parent | 08ca1d13d09b62765e6945ae7f1e33df3a156997 (diff) | |
download | tinygo-204659bdcd71e7601f077c246a97176a3e88075f.tar.gz tinygo-204659bdcd71e7601f077c246a97176a3e88075f.zip |
reflect: add TypeFor[T]
This function was added in Go 1.22. See:
https://github.com/golang/go/commit/42d2dfb4305aecb3a6e5494db6b8f6e48a09b420
Diffstat (limited to 'src/reflect')
-rw-r--r-- | src/reflect/type.go | 6 | ||||
-rw-r--r-- | src/reflect/type_test.go | 35 |
2 files changed, 41 insertions, 0 deletions
diff --git a/src/reflect/type.go b/src/reflect/type.go index bc45a41e4..56d4767f7 100644 --- a/src/reflect/type.go +++ b/src/reflect/type.go @@ -1313,3 +1313,9 @@ func uvarint32(buf []byte) (uint32, int) { } return 0, 0 } + +// TypeFor returns the [Type] that represents the type argument T. +func TypeFor[T any]() Type { + // This function was copied from the Go 1.22 source tree. + return TypeOf((*T)(nil)).Elem() +} diff --git a/src/reflect/type_test.go b/src/reflect/type_test.go new file mode 100644 index 000000000..75784f966 --- /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) + } + } +} |