In Go, it's a common practice to define function literals and pass them to higher-order functions. However, using range variables within function literals can raise concerns regarding variable scope.
In the following code snippet:
<code class="go">func TestGetUID(t *testing.T) { namespace := "lkfm" expecteduid := "fake_uid" var tests = []struct { description string expected string namespace string objs []runtime.Object }{ {"PositiveScenario", expecteduid, namespace, []runtime.Object{simpleNamespace(namespace)}}, } for _, x := range tests { t.Run(x.description, func(t *testing.T) { client := fake.NewSimpleClientset(x.objs...) actual := getUID(client, x.namespace) assert.Equal(t, x.expected, actual) }) } }</code>
The lint checker raises the error: "Using the variable on range scope x in function literal (scopelint)".
The error stems from using the loop variable x within the function literal passed to t.Run(). The compiler is unsure whether the function literal will be called after t.Run() returns. If it were, the function literal would refer to the loop variable, which could potentially be overwritten with the value from the next iteration.
To resolve the issue, modify the code to pass the value of the loop variable to the function literal or create a copy of it. Since the function signature is fixed, create a copy of the variable as follows:
<code class="go">x2 := x</code>
Then, refer to x2 within the function literal. This will satisfy the lint checker.
Alternatively, since the intention of making a copy is clear, the same name can be used for both the copy and the loop variable:
<code class="go">x := x</code>
This will shadow the loop variable and make it local to the function literal.
The above is the detailed content of How to Address \'Using the variable on range scope x in function literal (scopelint)\' in Go?. For more information, please follow other related articles on the PHP Chinese website!