Goroutines inside loops

In this code https://play.golang.org/p/wPt5RwYy3ij

package main

import (
	"time"
)

func main() {
	for i := 0; i < 2; i++ {
		go func() {
			println(i)
		}()
	}
	time.Sleep(1)
}

Outputs:

2
2

Why?

If inject i as a parameter to the routine function then it works fine. But I cannot understand why i is taking the highest length of the slice.

Have a look at this: https://play.golang.org/p/eCtEpBUM4wc

Basically the gofuncs are not executing until after the loop exits, this is why you typically work with channels of data you push values to and gofuncs will consume.

See this example for channel implementation: https://play.golang.org/p/duV3JgU4yWJ

3 Likes

You should also check this:

2 Likes

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