golang break语句可以break掉select,switch,for

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang break语句可以break掉select,switch,for相关的知识,希望对你有一定的参考价值。

坑,以下例子中,原本以为close掉done channel后,循环会退出。但事实上会进入死循环

for {
        select {
        case packet := <-s.avPacketChan:
            s.sendPacket(packet)
        case  <-s.done: //终止channel
            break
        }
    }

原因:
[A "break" statement terminates execution of the innermost "for", "switch" or "select" statement.

官方文档](https://golang.org/ref/spec#Break_statements)
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 // 从L标签处开始执行
      }
  }

以上是关于golang break语句可以break掉select,switch,for的主要内容,如果未能解决你的问题,请参考以下文章

Java中为啥我写switch语句,在case后加break就错误,不加就正确,很困惑,

break语句与continue语句

break和continue的区别

Java连载24-break语句continue语句输出质数练习

break和continue 的区别

Python入门教程第19篇 break语句