Does a break statement break from a switch/select?

后端 未结 7 1258
不知归路
不知归路 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条回答
  •  旧时难觅i
    2020-12-04 08:17

    Break statements, The Go Programming Language Specification.

    A "break" statement terminates execution of the innermost "for", "switch" or "select" statement.

    BreakStmt = "break" [ Label ] .
    

    If there is a label, it must be that of an enclosing "for", "switch" or "select" statement, and that is the one whose execution terminates (§For statements, §Switch statements, §Select statements).

    L:
      for i < n {
          switch i {
          case 5:
              break L
          }
      }
    

    Therefore, the break statement in your example terminates the switch statement, the "innermost" statement.

提交回复
热议问题