go - Passing parameters to function closure -


i'm trying understand difference in go between creating anonymous function takes parameter, versus having function act closure. here example of difference.

with parameter:

func main() {   done := make(chan bool, 1)   go func(c chan bool) {     time.sleep(50 * time.millisecond)     c <- true   }(done)   <-done } 

as closure:

func main() {   done := make(chan bool, 1)   go func() {     time.sleep(50 * time.millisecond)     done <- true   }()   <-done } 

my question is, when first form better second? ever use parameter kind of thing? time can see first form being useful when returning func(x, y) function.

the difference between using closure vs using function parameter has sharing same variable vs getting copy of value. consider these 2 examples below.

in closure function calls use value stored in i. value reach 3 before of goroutines has had time print it's value.

in parameter example each function call passed copy of value of i when call made, giving result more wanted:

closure:

for := 0; < 3; i++ {     go func() {         fmt.println(i)     }() } 

result:

3
3
3

parameter:

for := 0; < 3; i++ {     go func(v int) {         fmt.println(v)     }(i) } 

result:

0
1
2

playground: http://play.golang.org/p/t5rhrikrqv


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -