Passing parameters to function closure

The difference between using a closure vs using a function parameter has to do with sharing the same variable vs getting a copy of the value. Consider these two examples below.

In the Closure all function calls will use the value stored in i. This value will most likely already reach 3 before any of the goroutines has had time to print it’s value.

In the Parameter example each function call will get passed a copy of the value of i when the call was made, thus giving us the result we more likely wanted:

Closure:

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

Result:

3
3
3

Parameter:

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

Result:

0
1
2

Playground: http://play.golang.org/p/T5rHrIKrQv

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)