For {.en}

For 循环 {.zh}

::: {.en} for is Go’s only looping construct. Here are three basic types of for loops. :::

::: {.zh}

for是 Go 唯一的循环结构。这里有三种基本类型的 for 循环。

:::

  1. package main
  2. import "fmt"
  3. func main() {

::: {.en} The most basic type, with a single condition. :::

::: {.zh}

最基本的类型,具有单一条件。

:::

  1. i := 1
  2. for i <= 3 {
  3. fmt.Println(i)
  4. i = i + 1
  5. }

::: {.en} A classic initial/condition/after for loop. :::

::: {.zh}

经典的 初始/条件/后续 循环。

:::

  1. for j := 7; j <= 9; j++ {
  2. fmt.Println(j)
  3. }

::: {.en} for without a condition will loop repeatedly until you break out of the loop or return from the enclosing function. :::

::: {.zh}

没有条件的 for 将重复循环直到你在循环中使用 break 跳出循环或 return 结束函数。

:::

  1. for {
  2. fmt.Println("loop")
  3. break
  4. }

::: {.en} You can also continue to the next iteration of the loop. :::

::: {.zh}

你也可以使用 continue 跳到循环的下一次迭代。

:::

  1. for n := 0; n <= 5; n++ {
  2. if n%2 == 0 {
  3. continue
  4. }
  5. fmt.Println(n)
  6. }
  7. }
  1. $ go run for.go
  2. 1
  3. 2
  4. 3
  5. 7
  6. 8
  7. 9
  8. loop
  9. 1
  10. 3
  11. 5

::: {.en} We’ll see some other for forms later when we look at range statements, channels, and other data structures. :::

::: {.zh}

后续学习 range 语句,channels 以及其他数据结构时,我们将看到 for 循环的其他一些形式。

:::