Reflect TypeOf Kind Switch On Any
Dispatch any values through reflect.TypeOf with a Kind switch, so named types resolve to their underlying kind and slices or maps expose elem and key kinds.
Code
package main
import (
"fmt"
"reflect"
)
// describe 用 Kind 判定底层种类:具名类型不会骗过 Kind
func describe(v any) string {
t := reflect.TypeOf(v)
if t == nil {
return "nil interface"
}
switch t.Kind() {
case reflect.Int, reflect.Int64:
return fmt.Sprintf("int (%s)", t.Name())
case reflect.String:
return fmt.Sprintf("string (%s)", t.Name())
case reflect.Slice:
return fmt.Sprintf("slice of %s", t.Elem().Kind())
case reflect.Map:
return fmt.Sprintf("map %s -> %s", t.Key().Kind(), t.Elem().Kind())
case reflect.Struct:
return fmt.Sprintf("struct with %d fields", t.NumField())
default:
return fmt.Sprintf("unhandled kind %s", t.Kind())
}
}
type Config struct {
Workers int
Region string
}
func main() {
for _, v := range []any{
42, "workers", []int{1, 2}, map[string]string{"a": "b"}, Config{}, 3.14,
} {
fmt.Println(describe(v))
}
// 具名 int64:Kind 仍是 int64,Name 才是自定义名
type Handle int64
fmt.Println(describe(Handle(7)))
}Execution shape
Count the functions describe and main as the entire surface area of Reflect TypeOf Kind Switch On Any.
The one repetition in this snippet is the loop for _, v := range []any.
Applying it
Entry signature: func describe(v any) string
Treat main as the orchestrator calling describe in a fixed order.
Statements that matter
return fmt.Sprintf("map %s -> %s", t.Key().Kind(), t.Elem().Kind())
return fmt.Sprintf("struct with %d fields", t.NumField())
return fmt.Sprintf("slice of %s", t.Elem().Kind())
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
- How do you run Reflect TypeOf Kind Switch On Any?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.