0

Case 1

This program compiles successfully:

package main

import (
    "fmt"
)

func main() {
    i := 0
    for ; i < 3; i++ {
        fmt.Println(i)
    }
}

Case 2

But this does not:

package main

import (
    "fmt"
)

func main() {
    i := 0
    for ; i < 3; i++
    {
        fmt.Println(i)
    }
}

This leads to error:

./prog.go:9:18: syntax error: unexpected newline, expecting { after for clause

Case 3

But this compiles successfully:

package main

import (
    "fmt"
)

func main() {
    i := 0
    for
    {
        fmt.Println(i)
    }
}

Question

Why is it that in case 2, the opening brace for for is not allowed in the next line but in case 3 it is allowed?

Lone Learner
  • 18,088
  • 20
  • 102
  • 200
  • The last should probably not be allowed, it might be a bug, but it's not 100% clear from my reading of the spec based on https://golang.org/ref/spec#For_statements and https://golang.org/ref/spec#Blocks – Adrian Jul 28 '20 at 19:02
  • Why the downvotes? How could I have made this question better? – Lone Learner Aug 07 '20 at 17:12

2 Answers2

11

In short, when you have this in line:

for ; i < 3; i++

a semicolon will be inserted automatically, resulting in syntax error.

Spec: Semicolons:

When the input is broken into tokens, a semicolon is automatically inserted into the token stream immediately after a line's final token if that token is

So in Case 2 the lexer will automatically insert a semicolon at the end of the line which when present will "render" the code syntactically incorrect.

Not in Case 3 when there is only a for in a line, no semicolon is inserted (as per the quoted rules above, semicolon is only inserted after the break, continue, fallthrough and return keywords). So in Case 3 the code will not be extended with a semicolon and will remain syntactically correct.

For more details, see How to break a long line of code in Golang?

icza
  • 389,944
  • 63
  • 907
  • 827
-3
package main

import (
    "fmt"
)

func main() {
    i := 0
    for ; i < 3; i++{
        fmt.Println(i)
    }
}

works its just that putting { in a new line causes the error you get.

in case 3 you don't have any statement to evaluate, so new line doesn't cause an y problem.

whitespace
  • 789
  • 6
  • 13