# Loop variable not captured by goroutines

**URL:** <https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347>\
**Category:** Getting Help\
**Created:** [July 15, 2023, 10:09am UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347 "2023-07-15T10:09:15Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![panteliskar](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/panteliskar/32/13707_2.png) [@panteliskar](https://forum.golangbridge.org/u/panteliskar)\
**Post date:** [July 15, 2023, 10:09am UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/1 "2023-07-15T10:09:15Z")

</div>

Why does this fail (always prints `3`)

```go
func main() {

	for i := 0; i < 3; i++ {
		go func() {
			fmt.Println(i)
		}()
	}

	time.Sleep(1 * time.Second)
}

```

while this works?

```go
func main() {

	for i := 0; i < 3; i++ {
		func() {
			go fmt.Println(i)
		}()
	}

	time.Sleep(1 * time.Second)
}

```

---

<div class="post-metadata">

**Author:** ![NobbZ](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/nobbz/32/3096_2.png) [@NobbZ](https://forum.golangbridge.org/u/NobbZ)\
**Post date:** [July 15, 2023, 11:20am UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/2 "2023-07-15T11:20:48Z")

</div>

Because at the time the go routines are scheduled, `i` is 3.

If you want to use outer values in a goroutine, pass them when creating the goroutine:

```go
func main() {

	for i := 0; i < 3; i++ {
		go func(i int) {
			fmt.Println(i)
		}(i)
	}

	time.Sleep(1 * time.Second)
}

```

---

<div class="post-metadata">

**Author:** ![GonzaSaya](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/gonzasaya/32/4535_2.png) [@GonzaSaya](https://forum.golangbridge.org/u/GonzaSaya)\
**Post date:** [July 16, 2023, 6:16pm UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/3 "2023-07-16T18:16:56Z")

</div>

More info  
[https://eli.thegreenplace.net/2019/go-internals-capturing-loop-variables-in-closures/](https://eli.thegreenplace.net/2019/go-internals-capturing-loop-variables-in-closures/)

You can use go vet to avoid this issues

> **[vet command - cmd/vet - Go Packages](https://pkg.go.dev/cmd/vet)**
>
> Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string.

Or go lint (includes go vet)

> **[Introduction | golangci-lint](https://golangci-lint.run/)**
>
> Fast Go linters runner golangci-lint.

---

<div class="post-metadata">

**Author:** ![christophberger](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/christophberger/32/11391_2.png) [@christophberger](https://forum.golangbridge.org/u/christophberger)\
**Post date:** [July 17, 2023, 6:57am UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/4 "2023-07-17T06:57:00Z")

</div>

Go 1.21 will include an [experimental setting](https://github.com/golang/go/wiki/LoopvarExperiment) to change the loop variable behavior. It solves this problem as well as similar loop problems outside goroutine context that include, in one way or another, delayed evaluation of the captured loop variable.

The setting is experimental (that is, it must be enabled manually), because the Go team is extremely cautious about language changes that might break existing Go code.

---

<div class="post-metadata">

**Author:** ![pngreal](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/pngreal/32/13710_2.png) [@pngreal](https://forum.golangbridge.org/u/pngreal)\
**Post date:** [July 17, 2023, 1:47pm UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/5 "2023-07-17T13:47:28Z")

</div>

> [@christophberger](#):
>
> The setting is experimental (that is, it must be enabled manually)[,](https://pngreal.com) because the Go team is extremely cautious about language changes that might break existing Go code.

The Go team is extremely cautious about language changes that could damage existing Go code, hence the setting is experimental (i.e., it must be activated manually).

---

<div class="post-metadata">

**Author:** ![pngreal](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/pngreal/32/13710_2.png) [@pngreal](https://forum.golangbridge.org/u/pngreal)\
**Post date:** [July 17, 2023, 1:51pm UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/6 "2023-07-17T13:51:02Z")

</div>

> [@christophberger](#):
>
> The setting is experimental (that is, it must be enabled manually)[,](https://pngreal.com) because the Go team is extremely cautious about language changes that might break existing Go code.

The Go team is extremely cautious about language changes that could damage existing Go code[,](https://pngreal.com) hence the setting is experimental (i.e., it must be activated manually).

---

<div class="post-metadata">

**Author:** ![jarrodhroberson](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/jarrodhroberson/32/7694_2.png) [@jarrodhroberson](https://forum.golangbridge.org/u/jarrodhroberson)\
**Post date:** [July 17, 2023, 9:45pm UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/7 "2023-07-17T21:45:05Z")

</div>

this is expected behavior, every other language with threading that can use a closure type function works this exact same way.

you either need to capture the state inside the closure. the best and least surprising way is with an argument to the function. the other way is subtle and can be missed by even people experienced with the language by just assigning a variable in the local scope to the value at the time the instance of the function is created, most of the time you see this done in the worst way possible; variable shadowing, which in your case would look like. “clever” programmers use the “shorthand” implicit version that catches newbies and even themselves out later when they are reading the code.

```auto
func() {
    i := i
    go fmt.Println(i)
}()

```

an explicit function argument is the best way to convey the semantic that is required.

```auto
func(i int) {
	go fmt.Println(i)
}(i)

```

---

<div class="post-metadata">

**Author:** ![christophberger](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/christophberger/32/11391_2.png) [@christophberger](https://forum.golangbridge.org/u/christophberger)\
**Post date:** [July 18, 2023, 7:04am UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/8 "2023-07-18T07:04:03Z")

</div>

> [@jarrodhroberson](#):
>
> this is expected behavior, every other language with threading that can use a closure type function works this exact same way.

This might be true, but then, it is expected behavior only to those who know how other languages with threading work.

Many newcomers stumble upon that behavior and would regard the aforementioned `loopvar` experiment as more logical than the current behavior.

---

<div class="post-metadata">

**Author:** ![panteliskar](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/panteliskar/32/13707_2.png) [@panteliskar](https://forum.golangbridge.org/u/panteliskar)\
**Post date:** [July 18, 2023, 9:20am UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/9 "2023-07-18T09:20:36Z")

</div>

To all the answers given, I think we have made clear why the first case does **not** work.

What I am missing (but perhaps has been somehow answered) is why the second case, i.e

```go
func main() {

	for i := 0; i < 3; i++ {
		func() {
			go fmt.Println(i)
		}()
	}

	time.Sleep(1 * time.Second)
}

```

**does** work.

Here we don’t use a local scope variable nor do we use an argument to the anonymous function used by the loop.

---

<div class="post-metadata">

**Author:** ![system](https://forum.golangbridge.org/uploads/default/original/2X/5/5ad234f7c3dbc68b6cc72d338ce4f2973d9fd81c.png) [@system](https://forum.golangbridge.org/u/system)\
**Post date:** [October 16, 2023, 9:20am UTC](https://forum.golangbridge.org/t/loop-variable-not-captured-by-goroutines/32347/10 "2023-10-16T09:20:48Z")

</div>

Closed on October 16, 2023, 9:20am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
