Short variable declaration


Short variable declaration is a very convenient manner of “declaring variable” in Go:

  1. i := 10

It is shorthand of following (Please notice there is no type):

  1. var i = 10

The Go compiler will infer the type according to the value of variable. It is a very handy feature, but on the other side of coin, it also brings some pitfalls which you should pay attention to:

(1) This format can only be used in functions:

  1. package main
  2. i := 10
  3. func main() {
  4. fmt.Println(i)
  5. }

The compiler will complain the following words:

  1. syntax error: non-declaration statement outside function body

(2) You must declare at least 1 new variable:

  1. package main
  2. import "fmt"
  3. func main() {
  4. var i = 1
  5. i, err := 2, true
  6. fmt.Println(i, err)
  7. }

In i, err := 2, false statement, only err is a new declared variable, var is actually declared in var i = 1.

(3) The short variable declaration can shadow the global variable declaration, and it may not be what you want, and gives you a big surprise:

  1. package main
  2. import "fmt"
  3. var i = 1
  4. func main() {
  5. i, err := 2, true
  6. fmt.Println(i, err)
  7. }

i, err := 2, true actually declares a new local i which makes the global i inaccessible in main function. To use the global variable but not introducing a new local one, one solution maybe like this:

  1. package main
  2. import "fmt"
  3. var i int
  4. func main() {
  5. var err bool
  6. i, err = 2, true
  7. fmt.Println(i, err)
  8. }

Reference:
Short variable declarations.