Home  >  Article  >  Backend Development  >  Go language basics - switch statement

Go language basics - switch statement

Go语言进阶学习
Go语言进阶学习forward
2023-07-24 15:50:001460browse


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

    }
}

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

    }
}

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

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

执行[4]

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

Letter i is a vowel

无条件表达式 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)
    }

}

执行[5]

上面的代码中,switch 中没有表达式,因此它被认为是 true,将会对 case 语句进行判断,判断 case num >= 51 && num 05844f9e0147e3c0a8085ec1af24cee9 100,判断为 false,但是 fallthrough 会忽视这点,即使结果是 false,也会继续执行该 case 块。

所以程序输出:

25 is lesser than 50
25 is greater than 100

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

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

cannot fallthrough final case in switch

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

}

执行[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
        }
    }

}

执行[9]

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

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

Generated even number 18

需要注意的是,如果使用不带标签的 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!

Statement:
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete