4

Coming from a background in Java and C# I am very pleased with the brevity of Golang's ability to use the shortcut method for variable declaration for private variables within functions, which allows me to write:

x := 1.5

It reminds me of duck typing in a dynamic language such as Python. However, in declaring global variables outside of the scope of a function you still need to use the more verbose syntax of:

var x float64 = 1.5

I'm just wondering why the shortcut method works for private variables and not globals? I know that the designers of the language are quite experienced so I'm assuming that this isn't reflective of a feature overlooked. Is there a technical reason why this kind of type inference (and I realize that the := shortcut is not the same as proper type inference) wouldn't work at the global scope? It just seems somewhat inconsistent in terms of the design, and as an inexperienced Gopher I must admit to being thrown off by this on a couple of occasions. On the whole however I'm really enjoying Go.

user1503949
  • 357
  • 5
  • 10
  • Because all package-level declarations start with a keyword (import, type, func, const, var, etc). – thwd Nov 26 '14 at 17:08
  • @divan You're right it seems to be along the same lines as my question. I searched before asking it but somehow didn't run across this. Apologies for the duplication. I'd delete my question but there are now answers so I don't think it's possible. I'm sure it'll be marked as a duplicate shortly. – user1503949 Nov 26 '14 at 17:35

2 Answers2

5

See the Ian's answer in this thread: https://groups.google.com/forum/#!msg/golang-nuts/qTZemuGDV6o/IyCwXPJsUFIJ

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

divan
  • 2,591
  • 1
  • 17
  • 19
  • 4
    And [this topic](https://groups.google.com/forum/#!msg/golang-nuts/OqYL9lgsPQ4/udp0nPHPZTgJ) for some additional info: At the top level, var (or const or type or func) is necessary: each item must be introduced by a keyword for ur-syntactic reasons related to recognizing statement boundaries. With the later changes involving semicolons, it became possible, I believe, to eliminate the need for var in some cases, but since const, type, and func must remain, it's not a compelling argument. – Makpoc Nov 26 '14 at 17:16
1

Actually you don't need to specify type in many cases.

var x = 1.5

should work fine. It's probably as short as it can get and it's not much longer than local variable shortcut. So there is a shortcut for global.

As to why := can't be used, I would guess that calling out var makes code structure more consistent as other global constructs start with a keyword - func, const, import, type.

Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49