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
",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).
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.