📌  相关文章
📜  for loop golang - Go 编程语言(1)

📅  最后修改于: 2023-12-03 15:15:10.041000             🧑  作者: Mango

For Loop in Golang

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.

  1. for loop with a single condition
  2. for loop with an initialization, a condition, and a post statement
  3. for loop as a while loop
For Loop with a Single Condition

This 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.

For Loop with an Initialization, a Condition, and a Post Statement

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.

For Loop as a While 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.

Conclusion

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.