workerpool
workerpool copied to clipboard
What is the purpose of "r := r"?
Hi there,
I'm using your library on every project that I have. But there is a line in your example that I don't understand. I'm not an expert on Go, maybe it's something very basic. So forgive me if it's a silly question.
for _, r := range requests {
r := r
wp.Submit(func() {
fmt.Println("Handling request:", r)
})
}
Why we are re-defining r there at r := r? We already have the value of r. The code doesn't work without that line. It became a mystery for me.
All anonymous functions created in the body of the loop capture the two variables themselves (the addresses of the variables), not the values of the two variables.
http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html#closure_for_it_vars