Sobes.tech
Senior

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

sobes.tech AI

Answer from AI

This code has several errors related to the use of sync.WaitGroup and closures in goroutines.

  1. Passing WaitGroup by value: In the goroutine function func(wg sync.WaitGroup), the WaitGroup is passed by value, meaning it is copied. As a result, calling wg.Done() inside the goroutine decreases the counter of the copy, not the original object, which leads to wg.Wait() in main never unlocking.

    The correct way is to pass a pointer to the WaitGroup: func(wg *sync.WaitGroup) and call wg.Done().

  2. Issue with variable i in closure: The variable i is used inside the goroutine, but it is modified in the loop. Because of this, all goroutines may print the same value (usually 10).

    To fix this, pass i as a parameter to the anonymous function:

for i := 0; i < 10; i++ {
    wg.Add(1)
    go func(wg *sync.WaitGroup, val int) {
        defer wg.Done()
        fmt.Println(val)
    }(&wg, i)
}
  1. Final corrected code:
package main

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

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(wg *sync.WaitGroup, val int) {
            defer wg.Done()
            fmt.Println(val)
        }(&wg, i)
    }

    wg.Wait()
    fmt.Println("some text")
    time.Sleep(1 * time.Minute)
    fmt.Println("some text2")
}

Thus, it is important to pass a pointer to the WaitGroup and to fix the loop variable's value for correct goroutine operation and synchronization.

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