K
K
kolo20122017-03-28 01:16:36
go
kolo2012, 2017-03-28 01:16:36

Is this a feature or a bug?

There will always be 2

package main

import (
  "fmt"
  "sync"
)

func main() {
  q := []string{"1", "2"}
  wg := new(sync.WaitGroup)
  for _, val := range q {
    wg.Add(1)
    go func(){
      fmt.Println(val)
      wg.Done()
    }()
  }
  wg.Wait()
}

https://play.golang.org/p/pSwQVmjsV-

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dasha Tsiklauri, 2017-03-28
@dasha_programmist

read about closures ( frequent mistakes of beginners ), how a variable is captured so that the result is expected here is a code example

package main

import (
  "fmt"
  "sync"
)

func main() {
  q := []string{"1", "2"}
  wg := new(sync.WaitGroup)
  for _, val := range q {
    wg.Add(1)
    go func(tVal string){
      fmt.Println(tVal)
      wg.Done()
    }(val)
  }
  wg.Wait()
}

Here is another great article , after reading which you will not make such mistakes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question