# 05.01-For

&#x20;`for` statement 讓我們將一連串的 statements（一段程式區塊）重複很多次，我們用 `for` 重寫之前的程式，類似這樣：

```go
package main

import "fmt"

func main() {
    i := 1
    for i <= 10 {
        fmt.Println(i)
        i = i + 1
    }
}
```

一開始我們先建立一個命名為 `i` 的變數，用來儲存我們要印出的數字。接著我們用關鍵字 `for`  建立一個 `for` 迴圈，提供一個條件判斷式，判斷的結果是 `true` 或 `false`，最後提供一段要執行的程式碼。for 迴圈的運作方式類似這樣：

* 我們評估（執行）表示式 `i <= 10`（“i 小於或等於 10”）。 若此表示式的結果為真，則執行區塊內的程式碼；否則就跳躍至我們程式的區塊外第一行程式。（以此例而言，區塊之外沒有程式碼，而只是離開程式）。
* 在我們執行區塊內的 statements 之後，迴圈會回到區塊的起點，並重複上個步驟。

`i = i + 1` 這行相當重要，因為如果沒有這一行，那麼 `i <= 10` 就恆為真 `true`，因而我們的程式將不會停止（這種情況稱為無窮迴圈）。

當作是個習題，我們以電腦的角度來看這整個程式：

* 建立一個名為 `i` 的變數，初值設定為 1
* `i <= 10` 是否成立？是的。
* 印出 `i`
* 將 `i` 設定為 `i + 1`（`i` 目前等於 2）
* `i <= 10` 是否成立？是的。
* 印出 `i`
* 將 `i` 設定為 `i + 1`（`i` 現在等於 3）
* …
* 將 `i` 設定為 `i + 1`（`i` 現在等於 11）
* `i <= 10` 是否成立？否
* 沒事了，所以離開

別的程式語言有蠻多種迴圈類型（while、do、until、foreach、 …）但是 Go 只有一個能有各種用法的迴圈，之前的程式可以寫成這樣：

```go
func main() {
    for i := 1; i <= 10; i++ {
        fmt.Println(i)
    }
}
```

現在條件判斷式也包含了兩個 statements，在它們之間有分號隔開。首先我們初始化變數，接著每次都要檢查條件，最後將變數加 1。（用特殊運算符  `++` 將變數加 1 是很普遍的，同樣地，減  1 可以用  `--`）

我們在後面的章節將會看到更多迴圈的用法。


---

# 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://go.netdpi.net/control/05.01-for.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.
