Sobes.tech
Junior — Senior

Correctly output values from a set of goroutines

livecode

Task condition

It is necessary to launch a hundred goroutines, each of which should output its unique number. The expected output order is arbitrary, but the actual result differs from the expected. The task is to identify the reason for the incorrect output and propose a working solution that ensures correct value output.

package main

import (
  "fmt"
)

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