• golang学习笔记——switch 判断语句


    判断语句

    Go 语言提供了以下几种条件判断语句:

    语句描述
    if 语句if 语句 由一个布尔表达式后紧跟一个或多个语句组成。
    if…else 语句if 语句 后可以使用可选的 else 语句, else 语句中的表达式在布尔表达式为 false 时执行。
    if 嵌套语句你可以在 ifelse if 语句中嵌入一个或多个 ifelse if 语句。
    switch 语句switch 语句用于基于不同条件执行不同动作。
    select 语句select 语句类似于 switch 语句,但是select会随机执行一个可运行的case。如果没有case可运行,它将阻塞,直到有case可运行。

    注意:Go 没有三目运算符,所以不支持 ?: 形式的条件判断。

    本文只介绍switch语句


    基本 switch 语法

    像 if 语句一样,switch 条件不需要括号。 最简单形式的 switch 语句如下所示:

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    func main() {
        sec := time.Now().Unix()
        rand.Seed(sec)
        i := rand.Int31n(10)
    
    	switch i {
    	case 0:
    		fmt.Print("zero...")
    	case 1:
    		fmt.Print("one...")
    	case 2:
    		fmt.Print("two...")
    	default:
    		fmt.Print("no match...")
    	}
    
        fmt.Println("ok")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    switch 语句执行的过程从上至下,直到找到匹配项,匹配项后面也不需要再加 break。

    switch 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case。若要使逻辑进入到下一个紧邻的 case,请使用 fallthrough 关键字。

    使用多个表达式

    有时,多个表达式仅与一个 case 语句匹配。 在 Go 中,如果希望 case 语句包含多个表达式,请使用逗号 (,) 来分隔表达式。 此方法可避免代码重复。

    package main
    
    import "fmt"
    
    func location(city string) (string, string) {
        var region string
        var continent string
        switch city {
        case "Delhi", "Hyderabad", "Mumbai", "Chennai", "Kochi":
            region, continent = "India", "Asia"
    		break
        case "Lafayette", "Louisville", "Boulder":
            region, continent = "Colorado", "USA"
    		break
        case "Irvine", "Los Angeles", "San Diego":
            region, continent = "California", "USA"
    		break
        default:
            region, continent = "Unknown", "Unknown"
        }
        return region, continent
    }
    func main() {
        region, continent := location("Irvine")
        fmt.Printf("John works in %s, %s\n", region, continent)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    调用函数

    switch 还可以调用函数。 在该函数中,可以针对可能的返回值编写 case 语句。 例如,以下代码调用 time.Now() 函数。 它提供的输出取决于当前工作日。

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        switch time.Now().Weekday().String() {
        case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
            fmt.Println("It's time to learn some Go.")
        default:
            fmt.Println("It's the weekend, time to rest!")
        }
    
        fmt.Println(time.Now().Weekday().String())
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    从 case 语句调用函数

    从 case 语句调用函数。 例如,使用此方法可以通过正则表达式来匹配特定模式。 下面是一个示例:

    package main
    
    import "fmt"
    
    import "regexp"
    
    func main() {
        var email = regexp.MustCompile(`^[^@]+@[^@.]+\.[^@.]+`)
        var phone = regexp.MustCompile(`^[(]?[0-9][0-9][0-9][). \-]*[0-9][0-9][0-9][.\-]?[0-9][0-9][0-9][0-9]`)
    
        contact := "foo@bar.com"
    
        switch {
        case email.MatchString(contact):
            fmt.Println(contact, "is an email")
        case phone.MatchString(contact):
            fmt.Println(contact, "is a phone number")
        default:
            fmt.Println(contact, "is not recognized")
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    请注意,在这个例子中,switch 块没有任何验证表达式。 将在下面讨论该概念。

    省略条件

    在 Go 中,可以在 switch 语句中省略条件,就像在 if 语句中那样。 此模式类似于比较 true 值,就像强制 switch 语句一直运行一样。

    下面是一个示例,说明了如何编写不带条件的 switch 语句:

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    func main() {
        rand.Seed(time.Now().Unix())
        r := rand.Float64()
        switch {
        case r > 0.1:
            fmt.Println("Common case, 90% of the time")
        default:
            fmt.Println("10% of the time")
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    该程序始终运行这种类型的 switch 语句,因为条件始终为 true。 一个条件 switch 块比一长串的 if 和 else if 语句更易于维护。

    fallthrough 关键字

    在某些编程语言中,你会在每个 case 语句末尾写一个 break 关键字。 但在 Go 中,当逻辑进入某个 case 时,它会退出 switch 块,除非你显式停止它。 若要使逻辑进入到下一个紧邻的 case,请使用 fallthrough 关键字。

    若要更好地了解此模式,请查看以下代码示例。

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        switch num := 15; {
        case num < 50:
            fmt.Printf("%d is less than 50\n", num)
            fallthrough
        case num > 100:
            fmt.Printf("%d is greater than 100\n", num)
            fallthrough
        case num < 200:
            fmt.Printf("%d is less than 200", num)
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    运行代码并分析输出:

    15 is less than 50
    15 is greater than 100
    15 is less than 200
    
    • 1
    • 2
    • 3

    你是否看到错误?

    请注意,由于 num 为 15(小于 50),因此它与第一个 case 匹配。 但是,num 不大于 100。 由于第一个 case 语句包含 fallthrough 关键字,因此逻辑会立即转到下一个 case 语句,而不会对该 case 进行验证。 因此,在使用 fallthrough 关键字时必须谨慎。 该代码产生的行为可能不是你想要的。

  • 相关阅读:
    力扣:128. 最长连续序列(Python3)
    10数据结构与算法刷题之【排序算法】篇
    Pr:导出设置之编码设置
    【经验】怎么把Word文字下面的红线去掉?
    堆排序 ← 改编自《啊哈!算法》
    吴恩达老师机器学习课程笔记 07 正则化
    谈谈ORACLE应用数据同步器:Primavera Gateway (2/2)
    setup 中响应式数据的两种实现方法 & reactive API, ref,ReadOnly
    磁盘空间占满导致confluence6.3不可用问题修复流程
    关于Github报SSL_ERROR_SYSCALL的解决方案
  • 原文地址:https://blog.csdn.net/e891377/article/details/134434989