ZetCode

Go switch

最后修改时间 2024 年 4 月 11 日

在本文中,我们将介绍如何在 Golang 中使用 switch 语句。

Go switch 语句

Go switch 语句提供了一种多路执行方式。将表达式或类型说明符与 switch 中的 case 进行比较,以确定执行哪个分支。与其他语言(如 C、Java 或 PHP)不同,每个 case 都以隐式的 break 终止;因此,我们不必显式编写它。

Switch case 从上到下评估 case,并在 case 成功时停止。Switch 语句适用于任何类型的值,而不仅仅是整数。

Switch 语句有两种类型:switch 表达式和 switch 类型。我们可以使用逗号分隔同一个 case 语句中的多个表达式。不带表达式的 switch 是表达 if/else 逻辑的另一种方式。

当没有其他 case 匹配时,可以使用 `default` 语句来执行某个分支。`default` 语句是可选的。

Go switch 示例

以下是一个 Go 中 switch 语句的简单示例。

weekday.go
package main

import (
    "fmt"
    "time"
)

func main() {

    switch time.Now().Weekday() {

    case time.Monday:
        fmt.Println("Today is Monday.")
        
    case time.Tuesday:
        fmt.Println("Today is Tuesday.")
        
    case time.Wednesday:
        fmt.Println("Today is Wednesday.")
        
    case time.Thursday:
        fmt.Println("Today is Thursday.")
        
    case time.Friday:
        fmt.Println("Today is Friday.")
        
    case time.Saturday:
        fmt.Println("Today is Saturday.")
        
    case time.Sunday:
        fmt.Println("Today is Sunday.")
    }
}

在代码示例中,我们找出当前是星期几并打印相应的消息。

switch time.Now().Weekday() {

`switch` 语句接受一个表达式,该表达式计算为当前星期几。

case time.Monday:
    fmt.Println("Today is Monday.")

如果 weekday 计算结果为 `time.Monday`,我们将打印“今天是星期一”的消息。

Go switch 多表达式

可以在一个 case 中放置多个表达式。

weekday2.go
package main

import (
    "time"
    "fmt"
)

func main() {

    switch time.Now().Weekday() {
        
    case time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday:
        fmt.Println("weekday")
    case time.Saturday, time.Sunday:
        fmt.Println("weekend")
    }
}

该示例根据两个 case 语句中多个表达式的评估结果,打印“工作日”或“周末”。

Go switch default

`default` 语句可用于所有不符合指定 case 的值。

sizes.go
package main

import (
    "fmt"
)

func main() {

    size := "XXXL"

    switch size {

    case "XXS":
        fmt.Println("extra extra small")

    case "XS":
        fmt.Println("extra small")

    case "S":
        fmt.Println("small")

    case "M":
        fmt.Println("medium")

    case "L":
        fmt.Println("large")

    case "XL":
        fmt.Println("extra large")

    case "XXL":
        fmt.Println("extra extra large")

    default:
        fmt.Println("unknown")
    }
}

该示例检查衣服的尺码。如果使用了未识别的值,它将在终端打印“未知”。

Go switch 可选语句

可选的初始化语句可以放在 switch 表达式之前。初始化语句和表达式用分号分隔。

number.go
package main

import (
    "fmt"
)

func main() {

    switch num := 6; num % 2 == 0 {

    case true:
        fmt.Println("even value")

    case false:
        fmt.Println("odd value")
    }
}

在代码示例中,我们同时拥有 switch 初始化语句和表达式。switch 语句判断该值是偶数还是奇数。

switch num := 6; num % 2 == 0 {

`num := 6` 是 switch 初始化语句,而 `num % 2` 是 switch 表达式。

Go switch break 语句

Go 为每个 case 使用隐式的 `break` 语句。这与 C 或 Java 等语言不同,在这些语言中 `break` 是必需的。我们也可以根据需要显式指定 `break`。

explicit_break.go
package main

import (
"fmt"
)


func main() {

    w := "a b c\td\nefg hi"

    for _, e := range w {

        switch e {
        case ' ', '\t', '\n': 
            break
        default:
            fmt.Printf("%c\n", e)
        }
    }
}

在代码示例中,我们遍历一个包含空格的字符串。只打印非空格字符。

w := "a b c\td\nefg hi"

字符串中有一个空格、一个制表符和一个换行符空格字符。

for _, e := range w {

我们使用 `for range` 循环遍历字符串元素。

switch e {
    case ' ', '\t', '\n': 
        break

如果我们遇到指定的三个空格字符,我们将使用 `break` 终止 `switch` 语句。

$ go run explicit_break.go 
a
b
c
d
e
f
g
h
i

Go switch 无表达式

当不带表达式使用时,`switch` 语句实际上等同于 `switch true`。这种形式可以替代多行 if/else 语句来缩短代码。

noon.go
package main

import (
    "time"
    "fmt"
)

func main() {

    now := time.Now()

    switch {
    case now.Hour() < 12:
        fmt.Println("AM")

    default:
        fmt.Println("PM")
    }
}

根据当前的小时,该示例打印 `AM` 或 `PM`。

Go switch fallthrough

我们可以使用 `fallthrough` 关键字跳转到下一个 case。

fallthrough.go
package main

import (
    "fmt"
)

// A -> B -> C -> D -> E

func main() {

    nextstop := "B"

    fmt.Println("Stops ahead of us:")

    switch nextstop {

    case "A":
        fmt.Println("A")
        fallthrough

    case "B":
        fmt.Println("B")
        fallthrough

    case "C":
        fmt.Println("C")
        fallthrough

    case "D":
        fmt.Println("D")
        fallthrough

    case "E":
        fmt.Println("E")
    }
}

想象一下我们从 A 站前往 E 站。根据下一个可见的站点,我们确定还有多少站。

$ go run fallthrough.go 
Stops ahead of us:
B
C
D
E

Go type switch

通过 type switch,我们可以根据接口值的类型进行 switch。

type_switch.go
package main 

import "fmt"

func main() { 

    var data interface{} 
    
    data = 112523652346.23463246345

    switch mytype:= data.(type) { 
        
    case string: 
        fmt.Println("string")

    case bool: 
        fmt.Println("boolean") 

    case float64: 
        fmt.Println("float64 type") 

    case float32: 
        fmt.Println("float32 type") 

    case int: 
        fmt.Println("int") 

    default: 
        fmt.Printf("%T", mytype) 
    } 
} 

在代码示例中,我们打印值的数据类型。

case bool: 
    fmt.Println("boolean") 

对于 `bool` 类型,我们打印“boolean”。

$ go run type_switch.go 
float64 type

值为 `112523652346.23463246345` 是一个 `float64`。

来源

The Go Programming Language Specification

在本文中,我们介绍了 Golang 中的 switch 语句。

作者

我叫 Jan Bodnar,我是一名充满激情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Go 教程