Reflect TypeFor Static Types

Obtain reflect.Type without allocating a zero value using reflect.TypeFor, then compare types across interfaces and generics-driven code paths.

GoData Integrity

Code

gosnippet
36 lines
package main

import (
	"fmt"
	"reflect"
)

type Metric struct {
	Name  string
	Value float64
}

// Go 1.22 起 reflect.TypeFor[T] 在编译期取类型,不分配 T 的零值
// static type resolution without allocating a zero value
func typeName[T any]() string {
	return reflect.TypeFor[T]().Name()
}

func main() {
	fmt.Println("TypeFor int:", reflect.TypeFor[int]())
	fmt.Println("TypeFor struct:", reflect.TypeFor[Metric]())
	fmt.Println("TypeFor pointer:", reflect.TypeFor[*Metric]())

	// 运行期 any 值:TypeOf 动态取类型,接口为 nil 时返回 nil
	var v any = Metric{Name: "cpu", Value: 0.75}
	fmt.Println("TypeOf:", reflect.TypeOf(v))
	var empty any
	fmt.Println("TypeOf(nil any) == nil:", reflect.TypeOf(empty) == nil)

	// 类型可作 map 键:按类型分派的注册表
	registry := map[reflect.Type]string{
		reflect.TypeFor[int]():    "integer",
		reflect.TypeFor[string](): "text",
	}
	fmt.Println("registry lookup:", registry[reflect.TypeFor[string]()])
}

How it works

Everything happens inside the function main.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The signature that carries the file: func main()

The demo output is labeled (TypeFor int:, TypeFor struct:, TypeFor pointer:), so each line traces straight back to the statement that printed it.

Key statements

func typeName[T any]() string {
return reflect.TypeFor[T]().Name()
}

Interactive Tools for This Topic

FAQ

What does Reflect TypeFor Static Types print when run?
Run it as a complete program — the output lines carry labels such as `TypeFor int:`, `TypeFor struct:`, `TypeFor pointer:`.