Skip to content

reflect: add TypeFor #60088

Closed
Closed
@josharian

Description

@josharian

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions