📅  最后修改于: 2023-12-03 15:15:10.041000             🧑  作者: Mango
A loop is used to execute a block of code repeatedly. In Golang, the for
loop is used for this purpose.
There are three types of for
loop in Golang.
while
loopThis loop is used when you want to execute a block of code repeatedly until a condition is met.
for condition {
// code to be executed
}
Example:
for i := 1; i < 5; i++ {
fmt.Println(i) // prints 1, 2, 3, 4
}
In the above example, the block of code will be executed until the condition i < 5
is true.
This loop allows you to specify an initialization, a condition, and a post statement that are executed every time the loop runs.
for initialization; condition; post {
// code to be executed
}
Example:
for i := 1; i < 5; i++ {
fmt.Println(i) // prints 1, 2, 3, 4
}
In the above example, the initialization i := 1
is executed once before the first iteration of the loop. The condition i < 5
is checked before each iteration of the loop. The post statement i++
is executed after each iteration of the loop.
The for
loop in Golang can also be used as a while
loop.
for condition {
// code to be executed
}
Example:
i := 1
for i < 5 {
fmt.Println(i) // prints 1, 2, 3, 4
i++
}
In the above example, the loop will be executed until i < 5
is false.
The for
loop in Golang is an essential construct that every programmer must know. It can be used to execute a block of code repeatedly until a condition is met, or until a certain number of iterations have been executed.