|
Go-worm |
at Apr 13, 2014 at 5:40 pm
|
⇧ |
| |
Here's a way to think about it. Given that Go uses semicolons behind the
scenes, think in terms of its needing to 'know' where and where *not* to
put a semicolon to parse.
*1.* This is valid because Go doesn't insert a semicolon after a *for*.
func
test1() {
for
i := 0
i < 10
i++ {
fmt.Println(i)
}
}
*2.* Adding your own semicolons is also valid (but unconventional). Notice
that if test2() were on its own line, it wouldn't work, because Go normally
inserts a semicolon for lines that end in yourfunction() calls behind the
scenes.
func
test2() {
for
i := 0;
i < 10;
i++ {
fmt.Println(
i); // notice that it knows not to add a ; after ( above
};
};
*3.* Also valid because you added your own semicolons.
func test3() { for i := 0; i < 10; i++ { fmt.Println(i); }; };
*4.* Notice there are no semicolons for this compared to #2 but it's valid.
When it sees a line like i := 0 on its own, it thinks to normally insert a
semicolon. So it's added either way:
func test4() {
for
i := 0
i < 10
i++ {
fmt.Println(i)
}
}
*5.* Also valid:
func test5() {
i := 0
for
;
i < 10
{
fmt.Println(i)
i++
}
}
http://play.golang.org/p/E7hTE4V7ANIt's easiest to follow the conventions. If, however, you have a for line
that's hard on the eyes, then separate lines can help in
thinking/readability (like in example #4). This could also confuse people
looking quickly, into wondering why there's seemingly a lack of a left
bracket after for. It's your call.
On Saturday, April 12, 2014 12:34:51 PM UTC-5, Vasko Zdravevski wrote:Hi Gophers,
I've created a Gist of 4 different types of For statements, because I
noticed some versions of the for loop allow the block to begin on the next
line, while others do not. After reading the spec, I don't see that
distinction called out, so I'm wondering if this is a bug.
http://golang.org/ref/spec#For_statementsI tested on 1.2.1 and also latest TIP of the default branch at time of
this writing and Go Playground also behaves the same.
https://gist.github.com/vaskoz/10546740also providing same code in playground for convenience:
http://play.golang.org/p/v5FSCWZZPCIMPORTANT: DO NOT gofmt (either via command line or playground) the code,
as it actually changes the code in "CForLoopNoPrePost", which I also would
consider a bad thing as it's changing the kind of for statement.
These 4 examples came from
http://www.golangbootcamp.com/book/basic_concepts#sec-for-loopMany thanks all you helpful and responsive Gophers,
Vasko Zdravevski.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
[email protected].
For more options, visit
https://groups.google.com/d/optout.