27

This is allowed:

package main

var a = 3

...

But this isn't:

package main

a := 3

...

Why not? Why couldn't short variable declaration outside a function be treated regular declaration without a type? Just to simplify parsing?

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109

3 Answers3

42

According to Ian Lance Taylor in this thread shortly after the public announcement:

At the top level, every declaration begins with a keyword. This simplifies parsing.

Gustavo Niemeyer
  • 22,007
  • 5
  • 57
  • 46
8

To quote from The Go Programming Language Specification:

Short variable declarations may appear only inside functions. In some contexts such as the initializers for "if", "for", or "switch" statements, they can be used to declare local temporary variables.

You can think of var statement like const, type, and func, in the package level you have to specify what's kind of statement you are declaring.

Well , it's not a real shorthand , a, b := 12 can't compile, var a,b = 12 do.

Salah Eddine Taouririt
  • 24,925
  • 20
  • 60
  • 96
3

Outside a function, every statement must begin with a keyword (var, func, and so on), and so the := construct is not available.

See here. Hope it helps.

Matt
  • 74,352
  • 26
  • 153
  • 180
srini
  • 1,110
  • 3
  • 11
  • 20
  • Hi @Matt, just curious, what was the reason that you edited my answer? could you please share your feedback so that I can improve my answers in future. thank you. – srini May 27 '15 at 19:15