Golang闭包从范围中捕获错误的值

问题描述:

下面的测试代码:

func main() {
    lans := [5]string{"java", "python", "erlang", "cpp", "go"}
    fin := make(chan bool)
    for _, l := range(lans) {
        go func() {
            fmt.Println(l)
            }()
    }
     <- fin
}

我认为输出将是:java,python,erlang,cpp,go;但是输出是:去吧去吧去吧;怎么了?

I think the output will be: java, python, erlang, cpp, go; but the output is: go go go go go; what's wrong here?

只需编写这样的函数,即可将动词 l 捕获到函数中

just write the function like this, to catch the verb l into function

 go func(l string) {
     fmt.Println(l)
 }(l)