Friday, May 3, 2024
HomeGolangLoop variable not captured by goroutines - Getting Assist

Loop variable not captured by goroutines – Getting Assist


Why does this fail (at all times prints 3)

func predominant() {

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

	time.Sleep(1 * time.Second)
}

whereas this works?

func predominant() {

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

	time.Sleep(1 * time.Second)
}

As a result of on the time the go routines are scheduled, i is 3.

If you wish to use outer values in a goroutine, cross them when creating the goroutine:

func predominant() {

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

	time.Sleep(1 * time.Second)
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments