关于golang:轻松一刻Go-118修复了一个经典bug

16次阅读

共计 1309 个字符,预计需要花费 4 分钟才能阅读完成。

前言

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

declared but not used
比方上面的代码示例:

// example2.go
package main

func main() {

a := 10
a = 1

}
执行 go run example2.go,会报如下编译谬误:

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

起因

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

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

咱们来看一个新的例子,大家感觉上面的代码,执行 go run 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. 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 批改的探讨,感兴趣的能够参考 cmd/compile: consistently report “declared but not used” errors· Issue #49214。

开源地址

知乎上分享的所有 Go 常识和代码都开源在:https://github.com/jincheng9/…

也欢送大家关注微信公众号:coding 进阶,学习更多 Go、微服务和云原生架构相干常识。

正文完
 0