3 ms·
var i = 0; <--- valid i := 0 <--- Valid for (i := 0; ...) <--- Valid for (var i = 0; ...) <--- Invalid No?
by shadowmint 14y ago
var i = 0; <--- valid
i := 0 <--- Valid
for (i := 0; ...) <--- Valid
for (var i = 0; ...) <--- Invalid
No?
- jgrahamc 14y agoI'm not sure how much you know about Go based on your comment, but you have a ; in the first line that is not legal in Go (and you haven't declared the type); you have parens on your for loop and that too is not valid. If I rewrite your comment in correct Go I get var i int = 0 // valid i := 0 // valid for i := 0; ... { // valid for var i int = 0; ... { // Not valid Your final line there is only needed if you want to define the type of i at declaration time inside a for loop. That would be better written for i := int(0); ... {
- shadowmint 14y agoSure; I was just saying, the parent comment asked for an example of inconsistency there it is. Either allow the use of var to declare a variable, or dont. Dont mix and match in different contexts; this clearly violates the go goal of consistent syntax. Edit, incidentally the use of var is perfectly legal like this: package main import "fmt" func main() { var a = 10 b := 10 fmt.Printf("%d %d\n", a, b); for i := 0; i < 10; i++ { fmt.Printf("%d Value\n", i) } }
- swdunlop 14y agoActually, the following is valid syntax in Go 1.0 and later: var i = 0 The use of "var" without a type is a common idiom when binding global variables, such as: var ErrTooLarge = errors.New("bytes.Buffer: too large") Oddly, the := shortcut is not legal in the global context. Also fun: var ( i = 0 j = 0 ) So, going back to the original comment -- yes, Go has some odd little shortcuts and inconsistencies.
- StavrosK 14y agoWhy is := not valid in the global context? I have been bitten by this time and time again. Is there a reason for it? It makes no sense to me.
- burntsushi 14y agoI believe the answer is related to the simplicity of the parser.
- StavrosK 14y agoI see, thank you. Too bad this wart is exposed, though.