Sobes.tech
Junior — Senior

Closure correction and interaction with the scheduler

livecode

Task condition

The program needs to be fixed so that it reliably outputs numbers from 0 to 9. After fixing, explain how the Go scheduler distributes work internally. What results will the given code fragment produce when run on Go 1.21? How can you guarantee that all numbers from 0 to 9 will appear on the screen? Describe how the scheduler distributes goroutines and why this is related to how the loop variable is captured.

func main() {
    for idx := 0; idx < 10; idx++ {
        go func() {
            fmt.Println(idx)
        }()
    }
}