Sobes.tech
Middle+

// numbers from 1 to 10 func main() { done := make(chan struct{}, 10) for i:=1; i<=10; i++{ go func(){ defer func() {done<-struct{}{}}() printNumber(n) }() } for i:=1; i<=10; i++{ <-done } } func printNumber(n int) { time.Sleep(time.Second) fmt.Println(n) }

sobes.tech AI

Answer from AI

The provided code has several errors:

  1. The goroutine uses the variable n, which is not defined. You need to pass i as a parameter to the anonymous function to avoid closure issues.

  2. The done channel is created with a buffer of 10, which is not critical, but it can be unbuffered.

Corrected version:

package main

import (
    "fmt"
    "time"
)

func main() {
    done := make(chan struct{})

    for i := 1; i <= 10; i++ {
        go func(n int) {
            defer func() { done <- struct{}{} }()
            printNumber(n)
        }(i)
    }

    for i := 1; i <= 10; i++ {
        <-done
    }
}

func printNumber(n int) {
    time.Sleep(time.Second)
    fmt.Println(n)
}

Explanation:

  • Passing i as a parameter n in the goroutine captures the value for each iteration.
  • The done channel is used for synchronization — the main thread waits for all goroutines to finish.
  • printNumber outputs the number with a 1-second delay.

This way, the program correctly prints numbers from 1 to 10 (in any order, since goroutines run in parallel).

// numbers from 1 to 10 func main() { done :=… - sobes.tech