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;
}
}
}
讓我們編譯和運行上面的程序,這將產生以下結果:
1
2
3
4
5
6
|
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++;
}
}
讓我們編譯和運行上面的程序,這將產生以下結果:
1
2
3
4
5
6
7
8
9
|
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 |