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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.