preface

When writing Go, you should encounter the following compilation error:

declared but not used
Copy the code

For example:

// example2.go
package main

func main() {
	a := 10
	a = 1
}
Copy the code

If you run go example2.go, the following compilation error is reported:

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

why

The above error is actually due to the fact that the local variable must have been used as an r-value (right-hand-side-value) at least once for the standard Go compiler.

In the above example, the local variable a is an lvalue and is not used as an rvalue, so the compilation error is reported.

Let’s take a look at a new example. What do you think of the following code, go run example2.go?

// example2.go
package main

func main() {
	a := 10
	func() {
		a = 1
	}()
}
Copy the code

conclusion

In the example above, the local variable a was not used as an rvalue in the closure and would have compiled an error “declared but not used”.

But did you know that the Go standard compiler also has bugs on checks such as “declared but not used”?

The above code, if executed prior to Go1.18, results in no errors.

Go1.18 fixed a bug where local variables were not used in closures but the compiler did not declare an error. “declared but not used” was declared when Go1.18 started compiling.

The official instructions are as follows:

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.

14. Preferably report “declared but not used” errors· Issue #49214

Open source address

All Go knowledge and code shared on Zhihu is open source at: github.com/jincheng9/g…

We also welcome you to follow the wechat public account: Coding to learn more about Go, micro services and cloud native architecture.