Sobes.tech
Junior — Senior

Detection and fixing bugs in channels and goroutines

livecode

Task condition

In this exercise, you need to find and fix the issues in the provided code snippet that cause problems when working with channels and goroutines.

func main() {
    m := map[int]int{}

    wg := sync.WaitGroup{}
    var res chan int
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            m[i] = i
            res <- i
            wg.Done()
        }()
    }

    close(res)
    wg.Wait()
}

Pay attention to the correct initialization of channels, the order of closing, and the interaction with goroutine synchronization.