1

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)
}
2
  • The code is missing a closing brace } at the end. Adding it works as intended.
    – 6502
    Commented Jan 29, 2017 at 9:27
  • OK , sorry, copied it wrong. But what about declaring varibles, when should variables be declared and when shouldn't they be?
    – m_h
    Commented Jan 29, 2017 at 9:32

2 Answers 2

3

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.

1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.