Go 语言入门教程
类型 switch
本教程共 80 篇 · 第 43 篇 · 更新于 2026-07-27 · 约 6 分钟阅读
GoGo 入门教程类型switchtype switch接口类型断言
43. 类型 switch
本节目标:学会用类型 switch 一次判断多种类型,比连续类型断言更优雅。
类型 switch 语法
上一章学了类型断言 x.(T)。如果接口值可能是好几种类型,连续写 if-else 做断言很啰嗦。Go 提供了类型 switch 来解决这个问题:
switch v := x.(type) {
case Type1:
// v 是 Type1 类型
case Type2:
// v 是 Type2 类型
default:
// v 是其他类型
}
x.(type) 是类型 switch 的标志,注意它只能在 switch 语句里用,不能单独使用。
基本示例
package main
import "fmt"
func describe(v any) {
switch val := v.(type) {
case int:
fmt.Printf("整数: %d\n", val)
case string:
fmt.Printf("字符串: %s\n", val)
case bool:
fmt.Printf("布尔: %t\n", val)
case []int:
fmt.Printf("整数切片: %v\n", val)
default:
fmt.Printf("未知类型: %T\n", val)
}
}
func main() {
describe(42) // 整数: 42
describe("hello") // 字符串: hello
describe(true) // 布尔: true
describe([]int{1, 2}) // 整数切片: [1 2]
describe(3.14) // 未知类型: float64
}
每个 case 分支里,val 的类型就是该 case 指定的类型,不用再断言。比如 case int 里 val 就是 int,case string 里 val 就是 string。
Tip类型 switch 比连续
if-else做类型断言清晰得多。超过两种类型的判断就用类型 switch。
多类型合并
如果多种类型走同一个分支,可以用逗号分隔:
func describe(v any) {
switch v.(type) {
case int, int8, int16, int32, int64:
fmt.Println("整数类型")
case uint, uint8, uint16, uint32, uint64:
fmt.Println("无符号整数类型")
case float32, float64:
fmt.Println("浮点类型")
default:
fmt.Println("其他类型")
}
}
注意这种写法里 v 的类型是 any,因为编译器不知道具体是哪个类型。
判断接口类型
类型 switch 不只能判断基础类型,也能判断接口类型:
package main
import (
"fmt"
"io"
)
func processReader(r io.Reader) {
switch r.(type) {
case *io.LimitedReader:
fmt.Println("有限读取器")
case *io.SectionReader:
fmt.Println("分段读取器")
default:
fmt.Println("普通读取器")
}
}
不绑定变量
如果你只关心类型不关心值,可以省略变量名:
func checkType(v any) {
switch v.(type) {
case string:
fmt.Println("是字符串")
case int:
fmt.Println("是整数")
default:
fmt.Println("其他")
}
}
实际应用:处理不同错误类型
类型 switch 在错误处理中很常见:
package main
import (
"fmt"
"os"
)
func checkError(err error) {
switch e := err.(type) {
case *os.PathError:
fmt.Printf("路径错误: %s, 操作: %s\n", e.Path, e.Op)
case *os.LinkError:
fmt.Printf("链接错误: %s -> %s\n", e.Old, e.New)
default:
fmt.Printf("其他错误: %v\n", e)
}
}
小结
类型 switch 是处理接口值多类型的利器:
- 用
switch v := x.(type)语法 - 每个 case 里
v自动绑定到对应类型 - 多个类型可以合并到一个 case
- 也能判断接口类型,不只是基础类型
下一章讲空接口和 any 别名。