For {.en}
For 循环 {.zh}
::: {.en}
for is Go’s only looping construct. Here are
three basic types of for loops.
:::
::: {.zh}
for是 Go 唯一的循环结构。这里有三种基本类型的 for 循环。
:::
package mainimport "fmt"func main() {
::: {.en} The most basic type, with a single condition. :::
::: {.zh}
最基本的类型,具有单一条件。
:::
i := 1for i <= 3 {fmt.Println(i)i = i + 1}
::: {.en}
A classic initial/condition/after for loop.
:::
::: {.zh}
经典的 初始/条件/后续 循环。
:::
for j := 7; j <= 9; j++ {fmt.Println(j)}
::: {.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 结束函数。
:::
for {fmt.Println("loop")break}
::: {.en}
You can also continue to the next iteration of
the loop.
:::
::: {.zh}
你也可以使用 continue 跳到循环的下一次迭代。
:::
for n := 0; n <= 5; n++ {if n%2 == 0 {continue}fmt.Println(n)}}
$ go run for.go123789loop135
::: {.en}
We’ll see some other for forms later when we look at
range statements, channels, and other data
structures.
:::
::: {.zh}
后续学习 range 语句,channels 以及其他数据结构时,我们将看到 for 循环的其他一些形式。
:::
