Why reassign value from range loop in body of loop?

111 Views Asked by At

I stumbled upon something weird as I was writing tests. I have written a lot of table tests and I like the pattern recently I started working on a project that uses Ginkgo, and I wanted to write a table test like I am used to. I spent a few hours not understanding what was going on until I found this: https://github.com/onsi/ginkgo/issues/175#issuecomment-370015433

Which for some reason reassigns the range value in the body of the loop something like this:

for _, test := range tests {
    test := test
    It(test.it, func() {
        // test code reading values from the `test` variable
    })
}

I have done a lot of tests on the following form

for _, test := range tests {
    t.Run(test.name, func(t *testing.T) {
        // test code reading values from the `test` variable
    })
}

And I never had any issues with that. I am interested in what the difference is here.

0

There are 0 best solutions below