# 03.1.4 for循环代码示例

这一节将展示几个for循环的例子。这个代码示例的文件名是loops.go, 将被分为四部分进行展示。第一部分如下：

> ```go
> package main
>
> import (
>    "fmt"
> )
>
> func main() {
>    for i := 0; i < 100; i++ {
>        if i%20 == 0 {
>            continue
>        }
>        if i == 95 {
>            break
>        }
>        fmt.Print(i, " ")
> ```

上面的代码展示了一个典型的for循环的例子以及关键字continue和break的使用。

接下来的代码片段是：

> ```go
>    fmt.Println()
>    i := 10
>    for {
>        if i < 0 {
>            break
>        }
>        fmt.Print(i, " ")
>        i--
>    }
>    fmt.Println()
> ```

上面的代码模拟了一个典型的while循环。注意使用了关键字break来退出for循环。

第三段代码如下：

> ```go
>    i = 0
>    anExpression := true
>    for ok := true; ok; ok = anExpression {
>      if i > 10 {
>          anExpression = false
>         }
>       fmt.Print(i, " ")
>       i++ 
>   }
>    fmt.Println()
> ```

在这段代码中，你能看到前面所说的使用for循环来进行do...while循环的工作的操作。

loops.go的最后一部分展示如下：

> ```go
>    anArray := [5]int{0, 1, -1, 2, -2}
>    for i, value := range anArray {
>        fmt.Println("index:", i, "value: ", value)
>    }
> }
> ```

对一个数组使用range关键字会返回两个值：一个是数组的索引，一个是该索引上的值。你可以两个值都使用，或者使用其中一个，甚至如果你只是想单纯的计算一下数组的元素个数的话，也可以两个值都不使用。

执行loops.go会产生如下的输出：

> $ go run loops.go
>
> ```
> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 81 82 83 84 85 86 87 88 89 90 91 92 93 94
> 10 9 8 7 6 5 4 3 2 1 0
> 0 1 2 3 4 5 6 7 8 9 10 11
> index: 0 value:  0
> index: 1 value:  1
> index: 2 value:  -1
> index: 3 value:  2
> index: 4 value:  -2
> ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wskdsgcf.gitbook.io/mastering-go-zh-cn/3-go-ji-ben-shu-ju-lei-xing/03.1/03.1.4.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
