前言

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

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

// example2.go
package main

func main() {

a := 10a = 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 := 10func() {    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、微服务和云原生架构相干常识。