一个简单的类型开关:
// 假设x是类型interface {}的表达式
switch t := x.(type) {
case nil:
// x为零
// t将为interface {}类型
case int:
// x的基础类型为int
// 在这种情况下,t也将是int
case string:
// x的基础类型是字符串
// 在这种情况下,t也将是字符串
case float, bool:
// x的基本类型是float或bool
// 因为我们不知道哪个,所以在这种情况下,t是interface {}类型的
default:
// x的基础类型不是用于测试的任何类型
// t是这种类型的interface {}
}您可以测试任何类型,包括error,用户定义的类型,接口类型和函数类型:
switch t := x.(type) {
case error:
log.Fatal(t)
case myType:
fmt.Println(myType.message)
case myInterface:
t.MyInterfaceMethod()
case func(string) bool:
if t("Hello world?") {
fmt.Println("你好,世界!")
}
}