search
HomeBackend DevelopmentGolangGo language basics - switch statement

Go language basics - switch statement

Jul 24, 2023 pm 03:50 PM
go languageswitch statement


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

75 is greater than 51 and less than 100

这种类型的 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)
    }

}

执行[6]

switch 和 case 语句不只是常量,也可以在程序运行时计算得到。上面代码的第 14 行,num 使用 number() 函数的返回值初始化,第 18 行的 case 语句 case num

75 is lesser than 100
75 is lesser than 200

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

}

执行[7]

上面的代码中,num 等于 25,小于 50,所以第 9 行的 case 判断为 true,执行该语句。这个 case 语句最后一行是 fallthrough,继续执行下一个 case,不满足条件 case num > 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

跳出外部 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
Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools