HiI was playing around with closures and I noticed something curious.First, the obvious behavior. This prints five 5, as expected*:
for i := 0; i < 5; i++ {
go func() {time.Sleep(time.Millisecond)fmt.Println(i)}()}time.Sleep(2 * time.Millisecond)(* There is only one "i" variable in memory, the closure merely captures it. By the time the five goroutines stop sleeping, the single "i" already contains 5.)
This prints the numbers from 0 to 4 (in unpredictable order), again as expected:
for i := 0; i < 5; i++ {
go func(x int) {time.Sleep(time.Millisecond)fmt.Println(x)}(i)}time.Sleep(2 * time.Millisecond)
But the following surprised me. I expected it to "fail" (print five 5), instead it prints from 0 to 4:for i := 0; i < 5; i++ {x := igo func() {time.Sleep(time.Millisecond)fmt.Println(x)}()}time.Sleep(2 * time.Millisecond)
Why does a single (lexical) variable declaration cause many memory allocations? Would it always do so, or is this a case of the compiler being "smart" and noticing that the variable is being captured? More importantly, is this specified in the reference docs? Can it be relied upon?-Tobia--
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...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.