English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Loop control statements in Go language are used to change the execution of the program. When the execution of a given loop leaves its scope, the objects created within the scope are also destroyed. Go language supports3Types of loop control statements:
Break
Goto
Continue
The break statement is used to terminate the loop or statement it is in. Control is then passed to the statement following the break statement (if there is one). If the break statement exists within nested loops, it only terminates those loops that contain the break statement.
Flowchart:
package main import "fmt" func main() { for i:=0; i<5; i++{ fmt.Println(i) //For loop at i = 3then break if i == 3{ break; {} {} {}
Output:
0 1 2 3
This statement is used to transfer control to a labeled statement in the program. A label is a valid identifier placed before the control transfer statement. Due to the difficulty of tracking the control flow of the program, programmers usually do not use goto statements.
Flowchart:
package main import "fmt" func main() { var x int = 0 //The working principle of the for loop is the same as the while loop Label1: for x < 8 { if x == 5 { //Using goto statements x = x + 1; goto Label1 {} fmt.Printf("Value: %d\n", x); x++; {} {}
Output:
Value: 0 Value: 1 Value: 2 Value: 3 Value: 4 Value: 6 Value: 7
This statement is used to skip the execution part of the loop under specific conditions. After that, it transfers control back to the beginning of the loop. Essentially, it skips the following statements and continues to the next iteration of the loop.
Flowchart:
package main import "fmt" func main() { var x int = 0 //The working principle of the for loop is the same as the while loop for x < 8 { if x == 5 { //Skip two iterations x = x + 2 continue {} fmt.Printf("Value: %d\n", x) x++ {} {}
Output:
Value: 0 Value: 1 Value: 2 Value: 3 Value: 4 Value: 7