Golang的循环中break和continue语句的用法讲解
2019/7/10 22:11:06
本文主要是介绍Golang的循环中break和continue语句的用法讲解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Go语言break语句
在Go编程语言中的break语句有以下两种用法:
break语句用于在循环立即终止,程序控制继续下一个循环语句后面语句。
它可用于终止在switch语句的情况(case)。
如果你正在使用嵌套循环(即,一个循环在另一个循环中),break语句将停止最内层循环的执行,并开始执行的下一行代码的程序段之后。
语法
在Go break语句的语法如下:
break;
流程图:
例子:
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
/* for loop execution */
for a < 20 {
fmt.Printf("value of a: %d\n", a);
a++;
if a > 15 {
/* terminate the loop using break statement */
break;
}
}
}
让我们编译和运行上面的程序,这将产生以下结果:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15
Go语言continue语句
在Go编程语言中的continue语句有点像break语句。不是强制终止,只是继续循环下一个迭代发生,在两者之间跳过任何代码。
对于for循环,continue语句使循环的条件测试和执行增量部分。
语法
在Gocontinue语句的语法如下:
continue;
Flow Diagram:
例子:
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
/* do loop execution */
for a < 20 {
if a == 15 {
/* skip the iteration */
a = a + 1;
continue;
}
fmt.Printf("value of a: %d\n", a);
a++;
}
}
让我们编译和运行上面的程序,这将产生以下结果:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19
这篇关于Golang的循环中break和continue语句的用法讲解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-01got an unexpected keyword argument
- 2024-03-30维多利亚的秘密 golang入坑系统
- 2024-03-29mongodb sort by date
- 2024-03-29go swagger
- 2024-03-25mongodb cdc
- 2024-03-25how to use go in vscode
- 2024-03-22mongooseserverselectionerror: connect econnrefused ::1:27017
- 2024-03-21pymongo insert_many
- 2024-03-18projection mongodb
- 2024-03-14clickhouse-go