Both of those are declarations + assignments, not just an assignment.
There's no difference between them, except that the former may be used
at package level (i.e. outside a function), but the latter may not.
The other variation is "var x int = 2", which includes the type
information. "var x = 2" and "x := 2" infer the variable type from the
right-hand side, but "var x int = 2" explicitly sets it. You might
want to do that if, for instance, you want the variable to be typed
something different than what would be inferred, such as in "var x
int64 = 2", or "var r io.Reader = bytes.NewBuffer(foo)".
Dave.
I imagine that's why the differences were stated: one is short form, one
is long form. One has an optional initialiser, one doesn't.
If you're going to troll, at least get it right :).
--
Dr Rich Wareham
Current scope? How does the scope work in Go? I come from a mostly
javascript background where you have to watch yourself when making
variables so they don't go global, are the scopes better in go where
it's automatically local inside a function?
Current scope? How does the scope work in Go? I come from a mostly
javascript background where you have to watch yourself when making
variables so they don't go global, are the scopes better in go where
it's automatically local inside a function?
Current scope? How does the scope work in Go? I come from a mostly
javascript background where you have to watch yourself when making
variables so they don't go global, are the scopes better in go where
it's automatically local inside a function?
Just an "if you're interested" story. I noticed this the other day and
had to read around the spec to see what was going on. At first I
couldn't figure it out but later found this, for those that missed it:
* http://golang.org/doc/go_spec.html#Declarations_and_scope
"An identifier declared in a block may be redeclared in an inner
block. While the identifier of the inner declaration is in scope, it
denotes the entity declared by the inner declaration."
In my example, I had a var named 'url' (under r59) but with r60 gofix
renamed it to 'url_' so that was good. When playing I renamed it back
to 'url' and wondered whether it would conflict with the package name.
Everything still worked so this was an instance where the local 'url'
variable shadowed the imported package 'url'. To finish though, I
ended up naming my 'url' var to something completely different and
more useful.
Cheers,
Andy
--
Andrew Chilton
e: chi...@appsattic.com
w: http://www.appsattic.com/