Search code examples
govariablesscopevariable-declaration

Variable used inside function reported not used


This works fine:

package main

var foo string

func main() {
    fn := func() {
        foo = "AAA"
    }
    fn()
}

But if we move the variable declaration inside main():

package main

func main() {
    var foo string
    fn := func() {
        foo = "AAA"
    }
    fn()
}

— then it rants "foo declared and not used".

Why so?


Solution

  • The compiler can see in the second case that the assignment to foo is utterly pointless. The result of the assignment is never read. The code would work just as well without it. It is trying to be helpful.

    In the first case the compiler cannot be sure that foo as a global variable isn't used elsewhere.

    Although some modern compilers can spot this too and warn if variables are assigned and never used or worse are used before they have been assigned (or there is a path through the code where it could happen).