reflect: add TypeFor[T]
This function was added in Go 1.22. See:
42d2dfb430
Этот коммит содержится в:
родитель
08ca1d13d0
коммит
204659bdcd
2 изменённых файлов: 41 добавлений и 0 удалений
|
@ -1313,3 +1313,9 @@ func uvarint32(buf []byte) (uint32, int) {
|
||||||
}
|
}
|
||||||
return 0, 0
|
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()
|
||||||
|
}
|
||||||
|
|
35
src/reflect/type_test.go
Обычный файл
35
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Загрузка…
Создание таблицы
Сослаться в новой задаче