Does a break statement break from a switch/select?

后端 未结 7 1240
不知归路
不知归路 2020-12-04 07:57

I know that switch/select statements break automatically after every case. I am wondering, in the following code:

for {
    switch          


        
相关标签:
7条回答
  • 2020-12-04 08:21

    Yes, break breaks the inner switch.

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

    package main
    
    import "fmt"
    
    func main() {
    
    myloop:
        for x := 0; x < 7; x++ {
            fmt.Printf("%d", x)
            switch {
            case x == 1:
                fmt.Println("start")
            case x == 5:
                fmt.Println("stop")
                break myloop
            case x > 2:
                fmt.Println("crunching..")
                break
            default:
                fmt.Println("idling..")
            }
        }
    }
    
    0idling..
    1start
    2idling..
    3crunching..
    4crunching..
    5stop
    
    Program exited.
    
    0 讨论(0)
提交回复
热议问题