In the Go language, the break stop statement is used to jump out of the loop in a loop statement and start executing the statement after the loop. The break statement can end the code blocks of for, switch and select. In addition, the break statement can also add a label after the statement to indicate exiting the code block corresponding to a certain label. The label requirement must be defined on the corresponding code block of for, switch and select. .
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
When we use a for loop, when certain conditions are met, we need to terminate the loop's continued execution. In the Go language, the keyword used to terminate the loop's continued execution is break
.
In the Go language, the break stop statement is used to jump out of the loop in a loop statement and start executing the statement after the loop.
The break statement in Go language can end the code blocks of for, switch and select. In addition, the break statement can also add a label after the statement to indicate exiting the code block corresponding to a certain label. The label requirements must be defined. On the corresponding code blocks of for, switch and select.
break is the function of jumping out of the statement after executing a case in switch (switch statement).
In multiple loops, you can use label to mark the loop you want to break.
Grammar
break The syntax format is as follows:
break;
break statement flow chart is as follows:
Example
Break out of the loop when variable a is greater than 15:
package main import "fmt" func main() { /* 定义局部变量 */ var a int = 10 /* for 循环 */ for a < 20 { fmt.Printf("a 的值为 : %d\n", a); a++; if a > 15 { /* 使用 break 语句跳出循环 */ break; } } }
The following example has multiple loops, demonstrating the difference between using markers and not using markers:
package main import "fmt" func main() { // 不使用标记 fmt.Println("---- break ----") for i := 1; i <= 3; i++ { fmt.Printf("i: %d\n", i) for i2 := 11; i2 <= 13; i2++ { fmt.Printf("i2: %d\n", i2) break } } // 使用标记 fmt.Println("---- break label ----") re: for i := 1; i <= 3; i++ { fmt.Printf("i: %d\n", i) for i2 := 11; i2 <= 13; i2++ { fmt.Printf("i2: %d\n", i2) break re } } }
[Related recommendations: Go video tutorial, Programming teaching】
The above is the detailed content of What is the use of break stop statement in Go language?. For more information, please follow other related articles on the PHP Chinese website!