英文:
Why does vet complain that this variable is declared but not used?
问题
考虑以下Go程序:
package main
func a(fn func()) {
fn()
}
func main() {
var b int
a(func() {
b = 12
})
}
(在Go Playground上运行上述程序](https://play.golang.org/p/0HM4gUhs5jP))
b
在第8行声明,并在第10行赋值。然而,vet
报告如下警告:
<pre>vet.exe: test.go:8:2:
b declared but not used</pre>
如果确实使用了变量 b
,为什么会导致警告呢?
英文:
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:
<pre>vet.exe: test.go:8:2:
b declared but not used</pre>
Why does this cause a warning if it is indeed used?
答案1
得分: 4
变量的值从未被访问,只有被修改。因此,该变量没有产生任何效果。
只有当变量对程序的行为产生某种指定的影响时,才被认为是“被使用”。
尝试这样做,警告就会消失。
func main() {
var b int
a(func() {
b = 12
})
// 访问变量“b”的值
fmt.Println(b)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论