全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-14 6 分钟 ✍️ juanwangdev

Go类型选择

类型选择(type switch)是处理接口多种可能类型的便捷方式。

type switch语法

基本语法

Go
var i interface{} = "hello"

switch v := i.(type) {
case string:
    fmt.Println("字符串:", v)
case int:
    fmt.Println("整数:", v)
case bool:
    fmt.Println("布尔:", v)
default:
    fmt.Println("未知类型:", v)
}

type switch中v是具体类型的值,在每个case中类型确定。

无值类型选择

Go
switch i.(type) {
case string:
    fmt.Println("是字符串")
case int:
    fmt.Println("是整数")
default:
    fmt.Println("其他类型")
}

类型选择示例

处理多种输入类型

Go
func process(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Println("整数:", v, "平方:", v*v)
    case string:
        fmt.Println("字符串:", v, "长度:", len(v))
    case []int:
        fmt.Println("整数slice:", v)
    case map[string]int:
        fmt.Println("map:", v)
    default:
        fmt.Printf("未知类型: %T\n", v)
    }
}

process(42)         // 整数: 42 平方: 1764
process("hello")    // 字符串: hello 长度: 5
process([]int{1,2}) // 整数slice: [1 2]

自定义类型判断

Go
type User struct {
    Name string
    Age  int
}

func handle(v interface{}) {
    switch v := v.(type) {
    case User:
        fmt.Println("User:", v.Name, v.Age)
    case *User:
        fmt.Println("User指针:", v.Name, v.Age)
    default:
        fmt.Println("非User类型")
    }
}

nil类型处理

Go
switch v := i.(type) {
case nil:
    fmt.Println("nil值")
case string:
    fmt.Println("字符串:", v)
default:
    fmt.Println("其他")
}

nil是一个特殊的case,用于处理接口值为nil的情况。

多类型分支

Go
switch v := i.(type) {
case int, int32, int64:
    fmt.Println("整数类型:", v)
case float32, float64:
    fmt.Println("浮点类型:", v)
case string:
    fmt.Println("字符串:", v)
default:
    fmt.Println("其他")
}

多类型合并时,v在该case中为interface{}类型。

type switch vs 类型断言

特性type switch类型断言
处理类型多种类型单一类型
语法switch i.(type)i.(T)
类型检查自动匹配case手动判断
获取值每case自动转换需ok判断
适用场景多类型分支单类型检查

类型断言处理多类型对比

Go
// 类型断言方式(繁琐)
if v, ok := i.(int); ok {
    fmt.Println("int:", v)
} else if v, ok := i.(string); ok {
    fmt.Println("string:", v)
} else {
    fmt.Println("其他")
}

// type switch方式(简洁)
switch v := i.(type) {
case int:
    fmt.Println("int:", v)
case string:
    fmt.Println("string:", v)
default:
    fmt.Println("其他")
}

要点总结

  • type switch用i.(type)判断类型
  • case中v自动转换为具体类型值
  • nil case处理接口为nil的情况
  • 多类型合并用逗号分隔
  • type switch比多个断言更简洁
  • default处理未匹配类型
  • 无值type switch只判断类型不获取值

📝 发现内容有误?点击此处直接编辑

← 上一篇 Go类型断言
下一篇 → Go encoding/json包
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库