← 中文资源

简体中文版本

用 reflect.TypeFor 零分配取类型

Go 1.22 的 reflect.TypeFor[T]() 在编译期拿到 reflect.Type、不分配零值;运行期值仍用 TypeOf,类型还能作 map 键做按类型分派注册表。

阅读英文原文

实现说明

用 reflect.TypeFor 零分配取类型以函数 main为骨架。

使用要点

  • 每一步打印都带着自己的标签:TypeFor int:、TypeFor struct:、TypeFor pointer:。

常见问题

运行「用 reflect.TypeFor 零分配取类型」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 TypeFor int:、TypeFor struct:、TypeFor pointer: 标签标明各步骤。

核心语句

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

代码示例

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]()])
}