变量已声明但未使用

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

variable declared and not used

问题

我正在学习Go语言,但在尝试一个简单的for循环时,我发现很难让它正常工作。如果我在main函数中定义变量a,这段代码将无法编译,会出现错误"a declared but not used"。我不明白何时必须声明变量,何时不必声明。谢谢。

package main

import "fmt"

func main() {
    for a := 0; a < 4; a++ {
        fmt.Printf("a的值为%d\n", a)
    }
}
英文:

I am trying to learn Go, but when trying out a simple for loop, I found it difficult to get it working. This code does not compile if I define the variable a in the main function, it gives an error 'a declared but not used'. I don't understand when a variable must be declared and when it must not be. Thanks.

package main

import &quot;fmt&quot;

func main() {	
	
	
	for a:=0;a&lt;4;a++ {		
		fmt.Printf(&quot;value of a is %d\n&quot;,a)
}

答案1

得分: 3

你有两个可选项:

  1. 显式声明变量,然后使用:

     var a int
     a = 0
    
  2. 在一条语句中声明并赋值,无需指定类型(类型会被推断):

     a := 0
    

注意 =:= 的区别。如果你使用 := 两次,它会被视为重新声明。换句话说,= 只用于赋值,而 := 则用于在一步中声明和赋值。

英文:

You have two options available

  1. Declare the variable explicitly and then use

    var a int
    a = 0
    
  2. Declare and assign in one statement without having to specify the type (it is inferred)

    a:=0
    

Note the difference in = and :=. If you use := twice, it counts as a redeclaration. In other words, = is for assignment only, whereas := is for declaration and assignment in a single step.

答案2

得分: 1

你出现“not used error”的原因是因为表达式a:=0在循环的作用域中声明了一个同名的新变量。如果你在循环之前已经声明了变量a,请将其改为for a=0; a<4; a++(去掉冒号)。

英文:

The reason, you have the 'not used error', is because the expression a:=0 declares a new variable with the same name in the scope of the loop. If you already have the variable 'a' declared before the loop, change it to for a=0; a&lt;4; a++ (without the colon).

huangapple
  • 本文由 发表于 2017年1月29日 17:23:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/41919359.html
匿名

发表评论

匿名网友

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

确定