Sobes.tech
Senior

package main import ( "fmt" "sync" ) func main() { for i := 0; i < 5; i++ { go fmt.Println(i) } }

sobes.tech AI

Answer from AI

This code launches 5 goroutines, each of which prints the value of the variable i. However, because the variable i is used in a closure and changes in the loop, all goroutines may print the same value — usually 5, since by the time fmt.Println(i) executes, the loop has already finished.

To fix this, you should pass the current value of i to the goroutine as a parameter, for example:

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

This way, each goroutine gets its own copy of the value of i and will print numbers from 0 to 4.

Also, keep in mind that in the original code, the program might finish before the goroutines have a chance to execute their print statements, so for demonstration purposes, sync.WaitGroup or another synchronization method is often used to wait for goroutines to complete.

package main import ( "fmt" "sync" ) func main() {… - sobes.tech