Description
reflect.TypeOf
is one of a few fundamental reflect APIs. It returns the dynamic type of a value. This is, strictly speaking, sufficient. However, it is non-obvious how to use it to get a static type. The correct code is long, awkward, and hard to explain.
Pre-generics, there was no way to write a nice API to get a static reflect.Type. Now there is.
// MakeType returns the reflection Type that represents the static type of T.
func MakeType[T any]() reflect.Type {
return reflect.TypeOf((*T)(nil)).Elem()
}
I propose that we add it.
It is a single line implementation, but it fills an obvious gap in the package reflect API and makes call sites clear.
I strongly suspect that almost all uses would be in conjunction with reflect.Type.Implements
. An alternative would be make a generic version of implements that accepts an interface type as a type parameter, but fundamental building blocks compose better.
EDIT: this originally proposed StaticTypeOf
; renamed to MakeType
, per discussion.