0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Goの for ループにおけるクロージャの変数キャプチャ挙動

Posted at

このコードは、
for ループ内でクロージャ(closure)がループ変数をどのようにキャプチャするかを示しています。

package main

import "fmt"

func main() {
	var fns []func()
	for i := 0; i < 3; i++ {
		fns = append(fns, func() {
			fmt.Println(i)
		})
	}
	for _, fn := range fns {
		fn()
	}
}

Go 1.22 より前

上記のコードは 3 を3回出力します。

これは、無名関数がループ変数 i の参照(reference)をキャプチャしており、ループが終了する時点で i の値が 3 になっているためです。

出力例

3
3
3

Go 1.22 以降

Go 1.22 ではこの挙動が修正され、各ループの繰り返しで i は新しいローカル変数として扱われます。

そのため、期待どおりの 0 1 2 が出力されます。

出力例

0
1
2

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?