Passing parameters to function closure

前端 未结 2 1778
别跟我提以往
别跟我提以往 2020-12-29 05:33

I\'m trying to understand the difference in Go between creating an anonymous function which takes a parameter, versus having that function act as a closure. Here is an examp

2条回答
  •  半阙折子戏
    2020-12-29 06:15

    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

提交回复
热议问题