开放的编程资料库

当前位置:我爱分享网 > Go教程 > 正文

在Golang中使用switch语句

Goswitch教程展示了如何在Golang中使用switch语句。

$ go version
go version go1.18.1 linux/amd64

我们使用Go版本1.18。

转到switch语句

Goswitch语句提供了多路执行。将表达式或类型说明符与开关内的案例进行比较,以确定要执行的分支。与C、Java或PHP等其他语言不同,每个case都由隐式中断终止;因此,我们不必明确地写出来。

切换案例从上到下评估案例,当案例成功时停止。Switch语句适用于任何类型的值,而不仅仅是整数。

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

当没有其他情况适合时,default语句可用于执行的分支。default语句是可选的。

转到切换示例

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

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.")

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

去切换多个表达式

可以在一种情况下放置多个表达式。

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语句中多个表达式的评估。

转到默认值

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

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")
    }
}

该示例检查衣服的尺寸。如果使用了无法识别的值,它会向终端打印“未知”。

Goswitch可选语句

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

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 num := 6; num % 2 == 0 {

num:=6是开关初始值设定项,num%2是开关表达式。

转到switchbreak语句

Go对每种情况都使用隐式break语句。这与C或Java等语言不同,在这些语言中break是必需的。我们还可以在需要时显式指定break

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 {

我们使用forrange循环遍历字符串元素。

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

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

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

不带表达式去switch

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

package main

import (
    "time"
    "fmt"
)

func main() {

    now := time.Now()

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

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

根据当前时间,示例打印AMPM

去切换fallthrough

我们可以使用fallthrough关键字转到下一个案例。

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类型开关

通过类型开关,我们可以切换接口值的类型。

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

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

列出所有Go教程。

未经允许不得转载:我爱分享网 » 在Golang中使用switch语句

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏