英文:
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 "fmt"
func main() {
for a:=0;a<4;a++ {
fmt.Printf("value of a is %d\n",a)
}
答案1
得分: 3
你有两个可选项:
-
显式声明变量,然后使用:
var a int a = 0
-
在一条语句中声明并赋值,无需指定类型(类型会被推断):
a := 0
注意 =
和 :=
的区别。如果你使用 :=
两次,它会被视为重新声明。换句话说,=
只用于赋值,而 :=
则用于在一步中声明和赋值。
英文:
You have two options available
-
Declare the variable explicitly and then use
var a int a = 0
-
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<4; a++
(without the colon).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论