首页 > 后端开发 > Golang > 正文

为什么我在 Go 中收到'在函数文字中使用范围 x 上的变量”错误?

Barbara Streisand
发布: 2024-10-27 09:57:30
原创
545 人浏览过

Why am I getting a

在函数文字中使用范围范围 x 的变量

问题:

在下面的代码片段中,go vet工具报告错误:“在函数文字 (scopelint) 中使用范围范围 x 上的变量”。

<code class="go">func TestGetUID(t *testing.T) {
    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>
登录后复制

说明:

错误消息表明x 是一个循环变量,在传递给 t.Run() 的函数文字中使用。编译器无法保证在 t.Run() 返回后不会调用函数文字,这可能会导致数据争用或其他意外行为。

解决方案:

要解决此问题,您可以复制 x 并在函数文字中使用该副本:

<code class="go">func TestGetUID(t *testing.T) {
    for _, x := range tests {
        x2 := x // Copy the value of x
        t.Run(x2.description, func(t *testing.T) {
            client := fake.NewSimpleClientset(x2.objs...)
            actual := getUID(client, x2.namespace)
            assert.Equal(t, x2.expected, actual)
        })
    }
}</code>
登录后复制

或者,您可以通过将循环变量 x 分配给循环变量的新变量来隐藏它。函数文字中的名称相同:

<code class="go">func TestGetUID(t *testing.T) {
    for _, x := range tests {
        t.Run(x.description, func(t *testing.T) {
            x := x // Shadow the loop variable
            client := fake.NewSimpleClientset(x.objs...)
            actual := getUID(client, x.namespace)
            assert.Equal(t, x.expected, actual)
        })
    }
}</code>
登录后复制

以上是为什么我在 Go 中收到'在函数文字中使用范围 x 上的变量”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!