workerpool icon indicating copy to clipboard operation
workerpool copied to clipboard

What is the purpose of "r := r"?

Open utkusen opened this issue 3 years ago • 2 comments

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.

utkusen avatar Nov 16 '22 13:11 utkusen

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.

wj-stack avatar Nov 18 '22 03:11 wj-stack

http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html#closure_for_it_vars

hut8 avatar Feb 26 '23 01:02 hut8