14.9.2 类型 switch

类型 switch 语句比较类型而不是值。它由一个特殊的 switch 表达式 expression.(type) 标记:

switch x.(type) { /* case clauses */ }

switch y := x.(type) { /* case clauses */ }

在这种形式中,变量 y 绑定到断言的类型(可能为 nil)。

与表达式 switch 语句一样,类型 switch 表达式(任何形式)也可以由一个简单语句(和分号)前置,该语句在评估类型 switch 表达式之前执行。

case 子句具有以下语法:

case TypeList : StatementList

其中 TypeList 是一个逗号分隔的一个或多个类型列表。

在这种形式中,与表达式 x 的动态或运行时类型进行比较。与类型断言一样,x 必须是接口类型,并且在 case 中列出的每个非接口类型 T 都必须实现 x 的类型。

例子:

switch x := f(); t := x.(type) {
case int:
    fmt.Printf("Int x = %d\n", x)
case float64:
    fmt.Printf("Float64 x = %f\n", x)
case func(int) int:
    fmt.Println("x is a function of type 'func(int) int'")
default:
    fmt.Printf("The type of x is %v\n", t)
}

最后更新于