These answers are all correct. Here is another way to see the problem and address it. Not as clear to the next reader perhaps so not the recommendation, but a good example to contemplate. "Precisely what does this extra statement do?"
package main import "fmt" import "log" func main() { for i := 0; i < 5; i++ { i := i go func() { log.Println("i=", i) }() } fmt.Print("Press <Enter> to quit...") var input string fmt.Scanln(&input) } On Sun, Feb 12, 2017 at 3:12 AM, Ayan George <a...@ayan.net> wrote: > Srivathsan Madhavan <m.srivath...@gmail.com> wrote: > > > Hi all, > > > > I still consider myself a newbie to Golang hence my question here could > be > > due to my fundamental misunderstanding of this language > > > > I have the following code: > > > > func main() { > > > > for i := 0; i < 5; i++ { > > > > go func() { > > > > log.Println("i=", i) > > > > }() > > > > } > > > > > > fmt.Print("Press <Enter> to quit...") > > > > var input string > > > > fmt.Scanln(&input) > > > > } > > > > > > The output I expect is 0, 1, 2, 3, and 4 in any jumbled order. But what > I > > got was 5, 5, 5, 5 and 5! Why is that so? > > > > I'm learning golang too so please correct any errors here. > > It looks like you created a closure where i is lexically scoped to > each of your gofunc() instances. Since they're all accessing the same > i variable, you're seeing the race between incrementing i and spooling > up / starting each goroutine -- that is, the value of i reaches 5 > before all of the goroutines get to print it. You can verify this by > printing the address of i by changing your log.Println() call to > something like: > > log.Printf("i = %d, &i = %p", i, &i) > > The addresses should be the same. > > If you want each goroutine to have a copy of I, you should declare and > run gofunc() like below: > > gofunc(c int) { > log.Println("c=",c) > }(i) > > Which passes a copy of i to each routine. That should give you what > you're looking for -- that is if you're not expecting i to be printed > in order. :) > > -ayan > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > -- Michael T. Jones michael.jo...@gmail.com -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.