一、踩得坑

	for {
time.Sleep(p.Cfg.WatchInterval)
select {
case <-ctx.Done():
return default:
err := p.watchSomeThing(ctx)
if err != nil {
p.Error(zap.Error(errors.Wrap(err, "watch something")))
//continue
break //TODO:临时修改
}
}
}

最近项目中有上面一段代码,本来是为了临时修改在出错的时候能够退出最外层的for循环,简单的使用break,结果实际测试的时候仍然不起作用。后面发现其实是自己对break的用法理解还是不够透彻。

二、break的使用

1、break用于for循环

/* for 循环 */
for a < 20 {
fmt.Printf("a 的值为 : %d\n", a);
a++;
if a > 15 {
/* 使用 break 语句跳出循环 */
break;
}
}

例如上面的一段代码,即利用break跳出一个for循环。

2、 break用于select

    select {
case <-ch:
fmt.Println("This case is selected.")
break //The following statement in this case will not execute.
fmt.Println("After break statement")
default:
fmt.Println("This is the default case.")
}

例如上面一段代码,即利用break跳出一个select循环

3、break用于嵌套循环

	stopLable:
for {
time.Sleep(p.Cfg.WatchInterval)
select {
case <-ctx.Done():
return default:
err := p.watchSomeThing(ctx)
if err != nil {
p.Error(zap.Error(errors.Wrap(err, "watch something")))
//continue
break stopLable//TODO:临时修改
}
}
}

在 switch 或 select 语句中,break语句的作用结果是跳过整个代码块,执行后续的代码。但是嵌套循环时,只会跳出最内层的循环,最外层的for循环还是一直在跑。要想跳出最外层的循环可以在 break 后指定标签。用标签决定哪个循环被终止。

4、break label 、 goto label 、continue label

break label 和 goto label都能在循环中跳出循环,但是又有些不同之处。

  • break label:跳转标签(label)必须放在循环语句for前面,并且在break label跳出循环不再执行for循环里的代码。且break标签只能用于for循环
package main

import "fmt"

func main() {
outLable:
for i:=0; i< 5; i++{
fmt.Printf("外层:第%d次外层循环\n", i)
for j:=0; j< 5; j++ {
fmt.Printf("内层:第%d次内层循环\n", j)
break outLable
}
fmt.Printf("外层:没有跳过第%d次循环\n", i)
}
}

输出:

外层:第0次外层循环
内层:第0次内层循环
  • continue label: :跳转标签(label)必须放在循环语句for前面,跳出循环后则将继续执行lable后面的代码,即开始下一次外层循环
package main

import "fmt"

func main() {
outLable:
for i:=0; i< 5; i++{
fmt.Printf("外层:第%d次外层循环\n", i)
for j:=0; j< 5; j++ {
fmt.Printf("内层:第%d次内层循环\n", j)
continue outLable
}
fmt.Printf("外层:没有跳过第%d次循环\n", i)
}
}

输出:

外层:第0次外层循环
内层:第0次内层循环
外层:第1次外层循环
内层:第0次内层循环
外层:第2次外层循环
内层:第0次内层循环
外层:第3次外层循环
内层:第0次内层循环
外层:第4次外层循环
内层:第0次内层循环
  • goto lable:既可以定义在for循环前面,也可以定义在for循环后面,当跳转到标签地方时,继续执行标签下面的代码。
package main

import "fmt"

func main() {
outLable:
for i:=0; i< 5; i++{
fmt.Printf("外层:第%d次外层循环\n", i)
for j:=0; j< 5; j++ {
fmt.Printf("内层:第%d次内层循环\n", j)
goto outLable
}
fmt.Printf("外层:没有跳过第%d次循环\n", i)
}
}

输出:

外层:第0次外层循环
内层:第0次内层循环
外层:第0次外层循环
内层:第0次内层循环
外层:第0次外层循环
内层:第0次内层循环
外层:第0次外层循环
内层:第0次内层循环
外层:第0次外层循环
内层:第0次内层循环
......

5、官方解释

Break statements

A “break” statement terminates execution of the innermost “for”, “switch”, or “select” statement within the same function.

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.

OuterLoop:
for i = 0; i < n; i++ {
for j = 0; j < m; j++ {
switch a[i][j] {
case nil:
state = Error
break OuterLoop
case item:
state = Found
break OuterLoop
}
}
}

Continue statements

A “continue” statement begins the next iteration of the innermost “for” loop at its post statement. The “for” loop must be within the same function.

ContinueStmt = “continue” [ Label ] .

If there is a label, it must be that of an enclosing “for” statement, and that is the one whose execution advances.

RowLoop:
for y, row := range rows {
for x, data := range row {
if data == endOfRow {
continue RowLoop
}
row[x] = data + bias(x, y)
}
}

Goto statements

A “goto” statement transfers control to the statement with the corresponding label within the same function.

GotoStmt = “goto” Label .

goto Error

Executing the “goto” statement must not cause any variables to come into scope that were not already in scope at the point of the goto. For instance, this example:

	goto L  // BAD
v := 3
L:
is erroneous because the jump to label L skips the creation of v.

A “goto” statement outside a block cannot jump to a label inside that block. For instance, this example:

if n%2 == 1 {
goto L1
}
for n > 0 {
f()
n--
L1:
f()
n--
}

is erroneous because the label L1 is inside the “for” statement’s block but the goto is not.

参考文章

1、In Go, does a break statement break from a switch/select?

2、https://golang.org/ref/spec#Break_statements

3、Go语言之continue/break label(五)

go break的使用的更多相关文章

  1. continue break 区别

    在循环中有两种循环方式 continue , break continue 只是跳出本次循环, 不在继续往下走, 还是开始下一次循环 break  将会跳出整个循环, 此循环将会被终止 count = ...

  2. C# 中Switch case 返回不止用break

    Switch(temp) { case "A": //跳出循环 break; case "B": //返回值 return var; case "C& ...

  3. jquery each函数 break和continue功能

    jquery each函数 break和continue功能幸运的是另一个突破,持续一个jQuery循环方式.你可以打破在函数返回一个jQuery参数虚假循环.一个可以继续执行只是在做不指定返回值或返 ...

  4. [LeetCode] Integer Break 整数拆分

    Given a positive integer n, break it into the sum of at least two positive integers and maximize the ...

  5. [LeetCode] Word Break II 拆分词句之二

    Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...

  6. R for循环之break,next

    next跳出本次循环 break跳出本层循环(当有多个for 循环时,即跳出最近的一个for循环)

  7. 关于break语句如何结束多重循环的嵌套

    在Java中的break语句功能大体上同c语言, 用于循环语句中,表示结束当前循环. 但是有时候在循环嵌套语句中,仅仅靠一 个break语句想实现是不够的. 例: 如果想使sum在501时就直接输出, ...

  8. break与continue的区别

    break       在while.for.do...while.while循环中使用break语句退出当前循环,直接执行后面的代码. continue   的作用是仅仅跳过本次循环,而整个循环体继 ...

  9. 高程(3):操作符、for、for...in循环、break/continue/return语句、函数等

    1.关系操作符 注意点:1)比较操作数是两个字符串,是比较字符串的字符编码值. 如:"a" > "b"  返回 false:"a" & ...

  10. case break结构与return的有关要点

    //确认事件 private void cmd_ok_Click(object sender, EventArgs e) { //客户名称是否为空 if (txt_banhao.Text.TrimEn ...

随机推荐

  1. .netcore利用DI实现订阅者模式 - xms

    结合DI,实现发布者与订阅者的解耦,属于本次事务的对象主体不应定义为订阅者,因为订阅者不应与发布者产生任何关联 一.发布者订阅者模式 发布者发出一个事件主题,一个或多个订阅者接收这个事件,中间通过事件 ...

  2. 私有git搭建

    Git简介(目前世界上最先进的分布式版本控制系统) 那什么是版本控制系统? 你可以把一个版本控制系统(缩写VCS)理解为一个特殊的“数据库”,在需要的时候,它可以帮你完整地保存一个项目的快照.当你需要 ...

  3. SqlServer2005 查询 第三讲 between

    在数据库的查询中最重要的是要知道命令的顺序,因为在sql命令中有许多的参数,例如distinct,top,in,order by,group by.......如果你不能理解什么时候该执行什么的话,很 ...

  4. W5500

    W5500 芯片是一款韩国全硬件TCP/IP协议栈以太网接口芯片,   最近发现我们国内也有和W5500 芯片一样芯片 介绍给大家 如下图 :

  5. 从0开始学前端(笔记备份)----HTML部分 Day1 HTML标签

  6. 【阿里巴巴-高德-汽车事业部】【内推】Java技术专家、前端技术专家、C++技术专家(长期招聘)

    简历接收邮箱:yx185737@alibaba-inc.com 邮件请备注来自CSDN 一.Java技术专家 职位描述 研究汽车智能化和在线服务前沿技术,从事在线数据服务和车联网服务的设计和研发 负责 ...

  7. thinking in JAVA 编译记录

    编辑/编译<thinking in JAVA>源代码 一.下载源代码 首先,我阅读的是<thinking in JAVA>第四版,因此按照书中提供的链接找到了mindview主 ...

  8. Bran的内核开发教程(bkerndev)-08 中断服务程序(ISR)

    中断服务程序(ISR)   中断服务程序(ISR)用于保存当前处理器的状态, 并在调用内核的C级中断处理程序之前正确设置内核模式所需的段寄存器.而工作只需要15到20行汇编代码来处理, 包括调用C中的 ...

  9. js数组和集合互转

    js数组和集合互转可用于去重:   数组转集合 var arr = [55, 44, 65]; var set = new Set(arr); console.log(set.size === arr ...

  10. ArcGIS 切片与矢量图图层顺序问题

    在项目中有个需求:根据图层索引添加图层 看到这个需求一下子想到 map.addLayer(layer,index?) 接口 但是问题出现了,我切片图加载顺序在矢量图之后就不行! map = new M ...