Go language loop statements
In many practical problems, there are many regular repetitive operations, so it is necessary to repeatedly execute certain statements in programs.
The following is a flowchart of loop programs in most programming languages:
The Go language provides the following types of loop handling statements:
| Loop Types | Description |
|---|---|
| for Loop | Repeatedly execute statement block |
| Nested Loops | Nest one or more for loops inside a for loop |
Loop control statement
Loop control statements can control the execution process of statements within the loop body.
The Go language supports the following loop control statements:
| Control Statements | Description |
|---|---|
| break Statement | Often used to interrupt the current for loop or jump out of a switch statement |
| continue Statement | Skip the remaining statements of the current loop and then continue with the next round of the loop. |
| goto Statement | Transfer control to the labeled statement. |
Infinite Loop
If the condition statement in the loop is never false, an infinite loop will occur. We can execute an infinite loop by setting only one conditional expression in the for loop statement:
Example
package main
import "fmt"
func main() {
for true {
fmt.Printf("This is an infinite loop.\n");
}
}
import "fmt"
func main() {
for true {
fmt.Printf("This is an infinite loop.\n");
}
}