-1

Consider the following Go program:

package main

func a(fn func()) {
    fn()
}

func main() {
    var b int
    a(func() {
        b = 12
    })
}

(run above program on Go Playground)

b is declared on line 8 and a value is assigned on line 10. However, vet reports the following:

vet.exe: test.go:8:2:
  b declared but not used

Why does this cause a warning if it is indeed used?

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361

1 Answers1

4

The value of the variable is never accessed: only modified. Thus, the variable is never used to any effect.

The variable is only considered "used" if it has some specified effect on the behaviour of the program.

Try this, and the warning goes away.

func main() {
    var b int
    a(func() {
        b = 12
    })
    
    // Accessing the value "b"
    fmt.Println(b)
}
Hymns For Disco
  • 7,530
  • 2
  • 17
  • 33