Go language basics - switch statement

Release: 2023-07-24 15:50:00
forward
1475 people have browsed it


##What is a switch statement

switch is a conditional statement used to calculate the value of a conditional expression to determine whether the value satisfies the case statement. If it matches, the corresponding code block will be executed. is a common way to replace complex if-else statements.

Examples

An example is worth a thousand words. Let's look at a simple example where the input is the number of the finger and the output is the name of the phone, for example: 1 represents the thumb, 2 represents the index finger, etc.

package main

import (
    "fmt"
)

func main() {
    finger := 4
    fmt.Printf("Finger %d is ", finger)
    switch finger {
    case 1:
        fmt.Println("Thumb")
    case 2:
        fmt.Println("Index")
    case 3:
        fmt.Println("Middle")
    case 4:
        fmt.Println("Ring")
    case 5:
        fmt.Println("Pinky")

    }
}
Copy after login

Execution[1]

In the above code, the switch finger on line 10 will change the value of finger from top to bottom. Each case is compared and the code block of the first matching case is executed. In our example here, finger is 4, which matches case 4, so the output is: Finger 4 is Ring.

Duplicate cases are not allowed

case branches are not allowed to have the same constant value. If you try to run the following program, an error will be reported: ./prog.go:19:7: duplicate case 4 in switch previous case at ./prog.go:17:7

package main

import (
    "fmt"
)

func main() {
    finger := 4
    fmt.Printf("Finger %d is ", finger)
    switch finger {
    case 1:
        fmt.Println("Thumb")
    case 2:
        fmt.Println("Index")
    case 3:
        fmt.Println("Middle")
    case 4:
        fmt.Println("Ring")
    case 4: //duplicate case
        fmt.Println("Another Ring")
    case 5:
        fmt.Println("Pinky")

    }
}
Copy after login

Execution[2]

Default case

One There are only 5 fingers on a hand. What will happen if we enter the wrong finger number? At this time, the default branch can come in handy. If other branches do not match, the default branch will be executed.

package main

import (
    "fmt"
)

func main() {
    switch finger := 8; finger {
    case 1:
        fmt.Println("Thumb")
    case 2:
        fmt.Println("Index")
    case 3:
        fmt.Println("Middle")
    case 4:
        fmt.Println("Ring")
    case 5:
        fmt.Println("Pinky")
    default: //default case
        fmt.Println("incorrect finger number")
    }
}
Copy after login

Execution[3]

In the above code, when finger is equal to 8, it does not match any case branch. At this time, it will The default branch is executed, so the output is: incorrect finger number. In the switch statement, the default branch is not necessary and can be placed anywhere in the statement, but we generally place it at the end of the statement.

可能你已经注意到声明 finger 时的一点变化,它是在 switch 语句里面声明的。switch 包含一个可选语句,该语句在常量表达式匹配之前被执行。上面代码的第 8 行,先声明 finger,然后在条件表达式中被使用。这种情况下 finger 的作用局仅限于 switch 语句块内。

case 语句有多个表达式

case 语句中可以包括多个表达式,使用逗号分隔。

package main

import (
    "fmt"
)

func main() {
    letter := "i"
    fmt.Printf("Letter %s is a ", letter)
    switch letter {
    case "a", "e", "i", "o", "u": //multiple expressions in case
        fmt.Println("vowel")
    default:
        fmt.Println("not a vowel")
    }
}
Copy after login

执行[4]

上面的代码判断 letter 是否是元音。第 11 行代码的 case 分支用来匹配所有的元音,因为 "i" 是元音,所有输出:

Letter i is a vowel
Copy after login

无条件表达式 switch 语句

switch 中的表达式是可选的,可以省略。如果表达式省略,switch 语句可以看成是 switch true,将会对 case 语句进行条件判断,如果判断为 true 将会执行相应 case 的代码块。

package main

import (
    "fmt"
)

func main() {
    num := 75
    switch { // expression is omitted
    case num >= 0 && num <= 50:
        fmt.Printf("%d is greater than 0 and less than 50", num)
    case num >= 51 && num <= 100:
        fmt.Printf("%d is greater than 51 and less than 100", num)
    case num >= 101:
        fmt.Printf("%d is greater than 100", num)
    }

}
Copy after login

执行[5]

上面的代码中,switch 中没有表达式,因此它被认为是 true,将会对 case 语句进行判断,判断 case num >= 51 && num <= 100 为 true,所以输出:

75 is greater than 51 and less than 100
Copy after login

这种类型的 switch 被认为是多个 if-else 子句的替代方案。

fallthrough 语句

Go 语言里,执行完 case 语句的代码块将会立即跳出 switch 语句。使用 fallthrough 语句,可以在执行完该 case 语句后,不跳出,继续执行下一个 case 语句。

我们来写一个示例来好好理解下 fallthrough 语句。该示例将检查输入的数字是否小于 50、100 或 200。例如,如果我们输入 75,程序将打印 75 小于 100 和 200。我们将使用 fallthrough 来实现这一点。

package main

import (
    "fmt"
)

func number() int {
        num := 15 * 5
        return num
}

func main() {

    switch num := number(); { //num is not a constant
    case num < 50:
        fmt.Printf("%d is lesser than 50\n", num)
        fallthrough
    case num < 100:
        fmt.Printf("%d is lesser than 100\n", num)
        fallthrough
    case num < 200:
        fmt.Printf("%d is lesser than 200", num)
    }

}
Copy after login

执行[6]

switch 和 case 语句不只是常量,也可以在程序运行时计算得到。上面代码的第 14 行,num 使用 number() 函数的返回值初始化,第 18 行的 case 语句 case num < 100: 判断为 true,所以输出 75 is lesser than 100。执行完 case 语句,下一行代码是 fallthrough 语句,此时程序不会跳出,而是继续执行下一条 case,打印 75 is lesser than 200,所以程序输出:

75 is lesser than 100
75 is lesser than 200
Copy after login

fallthrough 语句必须是 case 语句块中最后一行代码,如果出现在 case 语句中间,编译时将会报错:fallthrough statement out of place。

即使 fallthrough 后面的 case 语句判定为 false,也会继续执行

使用 fallthrough 时需要注意一点,即使后面的 case 语句判定为 false,也会继续执行。

请看下面的代码:

package main

import (
    "fmt"
)

func main() {
    switch num := 25; {
    case num < 50:
        fmt.Printf("%d is lesser than 50\n", num)
        fallthrough
    case num > 100:
        fmt.Printf("%d is greater than 100\n", num)
    }

}</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px;padding-bottom: 8px;color: rgb(103, 97, 97);font-size: 17px;letter-spacing: 1.5px;line-height: 1.75;"><span style="font-weight: bold;color: #ee5408;">执行</span><sup style="line-height: 0;font-weight: bold;color: #ee5408;">[7]</sup></p>
<p data-tool="mdnice编辑器" style="padding-top: 8px;padding-bottom: 8px;color: rgb(103, 97, 97);font-size: 17px;letter-spacing: 1.5px;line-height: 1.75;">上面的代码中,num 等于 25,小于 50,所以第 9 行的 case 判断为 true,执行该语句。这个 case 语句最后一行是 fallthrough,继续执行下一个 case,不满足条件 case num > 100,判断为 false,但是 fallthrough 会忽视这点,即使结果是 false,也会继续执行该 case 块。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px;padding-bottom: 8px;color: rgb(103, 97, 97);font-size: 17px;letter-spacing: 1.5px;line-height: 1.75;">所以程序输出:</p>
<pre class="brush:php;toolbar:false;">25 is lesser than 50
25 is greater than 100
Copy after login

因此,请确保使用 fallthrough 语句时程序将会发生什么。

还有一点需要注意,fallthrough 不能用在最后一个 case 语句中,否则编译将会报错:

cannot fallthrough final case in switch
Copy after login

break

break 可以用来提前结束 switch 语句。我们通过一个示例来了解下工作原理:

我们添加一个条件,如果 num 小于 0,则 switch 提前结束。

package main

import (
    "fmt"
)

func main() {
    switch num := -5; {
    case num < 50:
        if num < 0 {
            break
        }
        fmt.Printf("%d is lesser than 50\n", num)
        fallthrough
    case num < 100:
        fmt.Printf("%d is lesser than 100\n", num)
        fallthrough
    case num < 200:
        fmt.Printf("%d is lesser than 200", num)
    }

}
Copy after login

执行[8]

上面的代码,num 初始化为 -5,当程序执行到第 10 行代码的 if 语句时,满足条件 num < 0,执行 break,提前结束 switch,所以程序不会有任何输出。

跳出外部 for 循环

当 for 循环中包含 switch 语句时,有时可能需要提前终止 for 循环。这可以通过给 for 循环打个标签,并且在 switch 语句中通过 break 跳转到该标签来实现。我们来看个例子,实现随机生成一个偶数的功能。

我们将创建一个无限 for 循环,并且使用 switch 语句判断随机生成的数字是否为偶数,如果是偶数,则打印该数字并且使用标签的方式终止 for 循环。rand 包的 Intn() 函数用于生成非负伪随机数。

package main

import (
    "fmt"
    "math/rand"
)

func main() {
randloop:
    for {
        switch i := rand.Intn(100); {
        case i%2 == 0:
            fmt.Printf("Generated even number %d", i)
            break randloop
        }
    }

}
Copy after login

执行[9]

上面代码的第 9 行,给 for 循环打了个标签 randloop。Intn() 函数会生成 0-99 的随机数,当为偶数时,第 14 行代码会被执行,跳转到标签 randloop 结束 for 循环。

程序输出(因为是随机数,你的执行结果可能与下面的不通):

Generated even number 18
Copy after login

需要注意的是,如果使用不带标签的 break 语句,则只会中断 switch 语句,for 循环将继续运行,所以给 for 循环打标签,并在 switch 内的 break 语句中使用该标签才能终止 for 循环。

switch 语句还可以用于类型判断,我们将在学习 interface 时再来研究这点。

via: https://golangbot.com/switch/
作者:Naveen R

参考资料

[1]

执行: https://play.golang.org/p/94ktmJWlUom

[2]

执行: https://play.golang.org/p/7qrmR0hdvHH

[3]

执行: https://play.golang.org/p/Fq7U7SkHe1

[4]

执行: https://play.golang.org/p/AAVSQK76Me7

[5]

Execution: https://play.golang.org/p/KPkwK0VdXII

[6]

Execution: https://play.golang.org/p/svGJAiswQj

##[7]Execution:

https://play.golang.org/p/sjynQMXtnmY

[8]Execution:

https ://play.golang.org/p/UHwBXPYLv1B

[9]Execution:

https://play.golang.org /p/0bLYOgs2TUk


## Recommended reading:
Weekly Article Express (3.21-3.27)

##Data download

Click on the card below Follow the official account and send specific keywords to get corresponding high-quality information!

  • # Reply to "E-book" to get must-read books for introductory and advanced Go language.

  • Reply to "Video" and get video information worth 5,000 oceans, including actual combat projects (not leaked)!

  • Reply to "Route" to get the latest version of Go knowledge map and learning and growth roadmap.

  • Reply to "Interview Questions" and get the Go language interview questions compiled by Brother Si, including analysis.

  • # Reply to "Backstage" to get the 10 must-read books on backend development.


By the way, after reading the article, remember to click on the card below. Follow me~ ???

------------------- End -------------- -----

Recommended articles from previous issues:

  • #Teach you step by step how to implement Golang cross-platform compilation#

  • #Golang performance diagnosis is enough to read this article #

  • #Build your own JA3 fingerprint with Go#

  • #shock! There is such a neat little function in Go! #

Go language basics - switch statement

#Welcome everyoneLike,Repost,Reprint,Thank you for your company and support

If you want to join the study group, please reply in the background【 Join the group

Love is always the same across thousands of rivers and mountains, can you click [在看]

The above is the detailed content of Go language basics - switch statement. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Go语言进阶学习
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template