简体   繁体   English

声明和未使用的变量

[英]variable declared and not used

I am trying to learn Go, but when trying out a simple for loop, I found it difficult to get it working. 我正在尝试学习Go,但是在尝试一个简单的for循环时,我发现很难让它工作。 This code does not compile if I define the variable a in the main function, it gives an error 'a declared but not used'. 如果我在main函数中定义变量a,则此代码不会编译,它会给出错误'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)
}

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. 换句话说, =仅用于赋值,而:=用于单个步骤中的声明和赋值。

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. 你有“未使用的错误”的原因是因为表达式a:=0在循环范围内声明了一个具有相同名称的新变量。 If you already have the variable 'a' declared before the loop, change it to for a=0; a<4; a++ 如果已经在循环之前声明了变量'a',则将其更改for a=0; a<4; a++ for a=0; a<4; a++ for a=0; a<4; a++ (without the colon). for a=0; a<4; a++ (没有冒号)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM