mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-08-03 02:27:48 +00:00
reflect: add TypeFor[T]
This function was added in Go 1.22. See: https://github.com/golang/go/commit/42d2dfb4305aecb3a6e5494db6b8f6e48a09b420
This commit is contained in:
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user