兽医为什么抱怨这个变量被声明但未使用?

huangapple go评论98阅读模式
英文:

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 &quot;b&quot;
	fmt.Println(b)
}

huangapple
  • 本文由 发表于 2021年11月12日 06:56:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/69935952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定