Sobes.tech
Senior

```go func main() { wg := sync.WaitGroup{} wg.Add(8) for i := 0; i < 10; i++ { go func(wg *sync.WaitGroup, i int) { defer wg.Done() fmt.Println(i) }(&wg,i) } wg.Wait() fmt.Println("some text") time.Sleep(1 * time.Minute) fmt.Println("some text2") } ```

sobes.tech AI

Answer from AI

The provided code contains several errors and potential issues:

  1. Typo in the function parameter: sync.WaitGrop instead of sync.WaitGroup.
  2. In the loop for i := 0; i < 10; i++, wg.Add(8) is called, but 10 goroutines are launched — this will lead to a deadlock because wg.Done() will be called 10 times, but the wait is only for 8.
  3. Passing the variable i into the closure is correct, as i is passed as a parameter, preventing the classic closure mistake in loops.

Corrected example:

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup

    wg.Add(10) // The number of goroutines should match the Add
    for i := 0; i < 10; i++ {
        go func(wg *sync.WaitGroup, i int) {
            defer wg.Done()
            fmt.Println(i)
        }(&wg, i)
    }
    wg.Wait()
    fmt.Println("some text")
    time.Sleep(1 * time.Minute)
    fmt.Println("some text2")
}

Thus, the code correctly creates 10 goroutines, each printing its value of i, then the main thread waits for all goroutines to finish, prints "some text", waits a minute, and then prints "some text2".

```go func main() { wg := sync.WaitGroup{} wg.Add(8)… - sobes.tech