实现说明
除了函数 describe、main,文件里再无其他定义。
本示例的循环部分是 for _, v := range []any{"config", 42, -3, []int{1, 2}, fmt.Errorf("boom"), 3.14}。
使用要点
- 运行整个文件:
main会依次驱动describe。
常见问题
「对 any 的类型分派」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
入口签名:func describe(v any) string
核心语句
for _, v := range []any{"config", 42, -3, []int{1, 2}, fmt.Errorf("boom"), 3.14} {
fmt.Println(describe(v))
}
return fmt.Sprintf("int slice of %d items", len(value))
return fmt.Sprintf("unsupported type %T", v)
代码示例
package main
import "fmt"
func describe(v any) string {
// type switch:一次遍历按具体类型分派
switch value := v.(type) {
case string:
return "text of length " + fmt.Sprint(len(value))
case int:
if value < 0 {
return "negative int"
}
return "non-negative int"
case []int:
return fmt.Sprintf("int slice of %d items", len(value))
case error:
return "error: " + value.Error()
default:
return fmt.Sprintf("unsupported type %T", v)
}
}
func main() {
for _, v := range []any{"config", 42, -3, []int{1, 2}, fmt.Errorf("boom"), 3.14} {
fmt.Println(describe(v))
}
}