Go: Unused local variables

As you may have noticed, programs with unused local variables do not compile:

func main() {
        var n int // "n declared and not used"
        n = 5     // this doesn't help
../main.go:2:6: n declared and not used

This is a deliberate feature of the Go language:

The presence of an unused variable may indicate a bug [...] Go refuses to compile programs with unused variables or imports, trading short-term convenience for long-term build speed and program clarity. Go FAQ: Can I stop these complaints about my unused variable/import?

Unused global variables and function arguments are however allowed.


There's no compiler option to allow unused local variables. If you don't want to remove/comment out the declaration, you can add a dummy assignment:

func main() {
        var n int
        n = 5
        _ = n  // n is now "used"


Be the first to comment!