Variable declarations
…
Implementation restriction: A compiler may make it illegal to declare a variable inside a function body if the variable is never used.
One short sentence. And people either love it, or hate it.
I’m in the “love it” camp, but some people like the option to create unused variables, for later use, or during debugging.
func foo() error {
var i int
// Some commented out code that probably used i
// ...
return nil
}
Fails to compile, complaining “i declared and not used”.
How can you get around this restriction?
Enter the blank identifier. We’ve talked about this guy before.
If you really want to keep around an unused variable, you need to fool the compiler into seeing it as used:
func foo() error {
var i int
_ = i
// Some commented out code that probably used i
// ...
return nil
}
Quotes from The Go Programming Language Specification Version of August 2, 2023