Go•ループ
Go の統合された for ループ:従来型、while 風、range 反復
Go ではすべてのループ構文が単一のキーワード for に統一されています。while や do-while を分けずに、3 要素カウンタ(for init; cond; post)、単一条件ループ(for cond)、無限ループ(for {})、range 句によるスライスやマップ走査を一貫して扱えます。
構文
for i := 0; i < 5; i++ { ... } // 3-component
for hasMore { ... } // while-style
for idx, val := range slice {} // range clause
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| for init; cond; post | Standard Loop | 初期化・条件・増分を備えた伝統的なカウンタループ。 |
| for condition | While-Style Loop | 条件が true のあいだ繰り返し実行します(Go における while 相当)。 |
| for idx, val := range | Range Clause | 配列、スライス、マップ、文字列、チャネルを反復してインデックスと値を取り出します。 |
そのまま実行できるコード例
Compilra で実行可能Go をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
package main
import "fmt"
func main() {
// 1. Classical 3-component counter loop
fmt.Println("=== 1. Three-Component Counter Loop ===")
for step := 1; step <= 3; step++ {
fmt.Printf("Step %d: Power of two = %d\n", step, 1<<step)
}
// 2. While-style single condition loop
fmt.Println("\n=== 2. While-Style Queue Halving Loop ===")
bufferSlots := 16
cycles := 0
for bufferSlots > 2 {
cycles++
fmt.Printf("Cycle %d: Active buffer slots = %d\n", cycles, bufferSlots)
bufferSlots /= 2
}
fmt.Printf("Buffer stabilized at %d slots\n", bufferSlots)
// 3. Range clause iteration over slice with index and copy
fmt.Println("\n=== 3. Slice Traversal via Range Clause ===")
pipelineMicroservices := []string{"auth-vault", "event-router", "db-writer"}
for idx, service := range pipelineMicroservices {
fmt.Printf("Service #%d: [%s] -> Operational\n", idx+1, service)
}
// 4. Value-only range iteration using blank identifier
fmt.Println("\n=== 4. Value-Only Traversal (Discarding Index) ===")
for _, service := range pipelineMicroservices {
fmt.Printf("Dispatched heartbeat probe to: %s\n", service)
}
}期待される出力:
=== 1. Three-Component Counter Loop === Step 1: Power of two = 2 Step 2: Power of two = 4 Step 3: Power of two = 8 === 2. While-Style Queue Halving Loop === Cycle 1: Active buffer slots = 16 Cycle 2: Active buffer slots = 8 Cycle 3: Active buffer slots = 4 Buffer stabilized at 2 slots === 3. Slice Traversal via Range Clause === Service #1: [auth-vault] -> Operational Service #2: [event-router] -> Operational Service #3: [db-writer] -> Operational === 4. Value-Only Traversal (Discarding Index) === Dispatched heartbeat probe to: auth-vault Dispatched heartbeat probe to: event-router Dispatched heartbeat probe to: db-writer
動作のしくみ: ステップ解説
- 7〜10行目: ビットシフト演算子(1<<step)を用いた 3 要素ループを示します。
- 14〜20行目: 単一条件の while 風ループで、条件を満たさなくなるまで bufferSlots を半減させます。
- 24〜27行目: range 句でスライスを反復し、0 始まりの idx と要素のコピー service を取得します。
- 31〜33行目: 値だけが必要な場合にブランク識別子 _ でインデックスを明示的に破棄します。
重要ポイント
- Go は最小限で直交的な言語文法を保つため、あえて while と do-while キーワードを省いています。
- 要素を省略した for { ... } は無限ループになり、通常は break や return で抜けます。
- range 句は値のコピーを返します。ループ内で val 変数を変更しても元のスライスは変わりません。
- range ループでインデックスだけが必要な場合は 2 番目の変数を省略し、for idx := range slice と書けます。
よくある間違い: range の反復変数のメモリアドレスを取得すること
古い Go バージョン(1.22 未満)では反復変数が使い回されていたため、クロージャ内で &val を取ると全反復で同じアドレスを指す問題が起きました。
❌ 誤り
for _, item := range list {
go func() { fmt.Println(&item) }() // Bug: shared address in pre-1.22!
}✅ 正しい例
for _, item := range list {
val := item
go func() { fmt.Println(&val) }() // Safe: local lexical copy
}