3 ms·
I know. The question is, why does it need a colon? It seems completely superfluous, from a syntax perspective.
by zubspace 7y ago
I know. The question is, why does it need a colon? It seems completely superfluous, from a syntax perspective.
- zchrykng 7y agoI think the point is to make sure you know what you are doing. That declaring a new variable should always be an intentional act, and this makes assignments to typoed variable names error rather than just creating a new variable.
- pkaye 7y agoIt catches some coding errors due to mispelling. Did you mispell an existing variable or wanted to declare a new one.
- zemo 7y agoit's not. Go has block-level scoping. = means "assign the existing identifier to this value". := means "create a new identifier". https://play.golang.org/p/Irqxm0okfkt https://play.golang.org/p/Irqxm0okfkt
- zubspace 7y agoThanks for the example. In all my life I never actually wanted to do something like this, but well... It's neat that go allows this.
- naikrovek 7y agoYou will if you ever do concurrency stuff in go. The way goroutines capture their working variables in a closure make things like `x := x` useful and clear (once you know why you do it in the first place )
- zemo 7y agothat's likely not true. Every time you do this: if err := fn(); err != nil { } // the result of fn does not affect the identifier err // in the enclosing scope you're scoping err just to that if block. that's ... just about the most common phrase in all of Go. it won't affect any err defined prior and it won't exist outside of the if block. You'd have to do this to make the value stick around or affect the enclosing block: var err error if err = fn(); err != nil { } // err has the result of fn here
- sacado2 7y agoIt's to avoid typos. Imagine there is no colon. When you type foo = 3 fooo = foo + 1 Did you mean to create a new variable called `fooo` or was it a typo? Did you mean this: foo := 3 fooo = foo + 1 // oops, typo found at compile-time or that: foo := 3 fooo := foo + 1 // Yep, new var, everything is ok
- philliphaydon 7y agoWhy not just have var foo = 1
- deleted 7y ago[deleted]
- masklinn 7y agoThat works actually. The weirdness is that ":=" allows redeclaration (within a scope) but only partial, whereas `var` completely forbids redeclaration. That is: var a, b = f() var a, b = f() // NO var a, b = f() a, b := f() // NO // note that the second declaration only partially overlaps with the first var a, b = f() var a, c = f() // NO var a, b = f() a, c := f() // yes