轻松一刻:Go 1.18修复了一个经典bug

2022年2月1日 248点热度 0人点赞 0条评论

背景

大家在写Go的时候,初期应该都会遇到过下面的编译报错:

xx declared but not used

比如下面的代码示例:

// example2.go
package main

func main() {
 a := 10
 a = 1
}

执行go build example2.go,会出现如下编译错误:

./example2.go:5:2: a declared but not used

原因

上面的报错,实际上是因为对于标准Go编译器,局部变量必须至少有一次被作为右值(r-value: right-hand-side-value)使用过。

上面的例子里局部变量a都是左值,并没有作为右值被使用过,因此编译报错。

我们来看一个新的例子,大家觉得下面的代码,执行go build example2.go的结果是什么?

// example2.go
package main

func main() {
 a := 10
 func() {
  a = 1
 }()
}

结论

按理来说,上面的示例里头,局部变量a在闭包里没有被作为右值使用过,还是应该会编译报错declared but not used

但是大家知道么,Go标准编译器对于declared but not used这样的检查,也会有bug。

上面的代码如果是Go1.18之前的版本,执行的话,结果是没有任何报错。

从Go1.18版本开始,解决了局部变量在闭包里没被使用但是编译器不报错的bug,Go1.18开始编译会报错”declared but not used“。

官方说明如下:

The Go 1.18 compiler now correctly reports "declared but not used" errors
for variables that are set inside a function literal but are never used. Before Go 1.18,
the compiler did not report an error in such cases. This fixes long-outstanding compiler
issue #8560[1].

As a result of this change,
(possibly incorrect) programs may not compile anymore. The necessary fix is
straightforward: fix the program if it was in fact incorrect, or use the offending
variable, for instance by assigning it to the blank identifier _.
Since go vet always pointed out this error, the number of affected
programs is likely very small.

关于这个bug修改的讨论,感兴趣的可以参考GitHub Issue[2]

开源地址

GitHub: Go初级、中级和高级教程[3]

公众号:coding进阶,获取最新Go面试题和技术栈

个人网站:https://jincheng9.github.io/[4],点击文章底部的阅读原文可以直接跳转

知乎:无忌[5]

参考资料

[1]

#8560: https://github.com/golang/go/issues/8560

[2]

GitHub Issue 49214: https://github.com/golang/go/issues/49214

[3]

https://github.com/jincheng9/go-tutorial: https://github.com/jincheng9/go-tutorial

[4]

https://jincheng9.github.io/: https://jincheng9.github.io/

[5]

无忌: https://www.zhihu.com/people/thucuhkwuji

73560轻松一刻:Go 1.18修复了一个经典bug

这个人很懒,什么都没留下

文章评论