wgwigw
wgwigw

Reputation: 11

golang closure catch wrong value from range

test codes below:

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

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

Upvotes: 0

Views: 137

Answers (1)

simon_xia
simon_xia

Reputation: 2544

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

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

Upvotes: 2

Related Questions