OscarRyz
OscarRyz

Reputation: 199333

syntax error: unexpected semicolon or newline, expecting }

I have this sample code where I'm defining an array but it doesn't compile:

$ cat a.go
package f
func t() []int  {
    arr := [] int {
        1,
        2
    }
    return arr
}

oreyes@OREYES-WIN7 ~/code/go
$ go build a.go
# command-line-arguments
.\a.go:5: syntax error: unexpected semicolon or newline, expecting }
.\a.go:7: non-declaration statement outside function body
.\a.go:8: syntax error: unexpected }

However if I remove the newline it works:

$ cat a.go
package f
func t() []int  {
    arr := [] int {
        1,
        2 }
    return arr
}

oreyes@OREYES-WIN7 ~/code/go
$ go build a.go

Howcome?

Upvotes: 13

Views: 31986

Answers (2)

user811773
user811773

Reputation:

Simply put a comma (,) at the end of all lines containing elements of the array:

arr :=  [] func(int) int {
    func( x int ) int { return x + 1 },
    func( y int ) int { return y * 2 }, // A comma (to prevent automatic semicolon insertion)
}

Upvotes: 27

Denys Séguret
Denys Séguret

Reputation: 382454

When the input is broken into tokens, a semicolon is automatically inserted into the token stream at the end of a non-blank line if the line's final token is

an identifier an integer, floating-point, imaginary, character, or string literal one of the keywords break, continue, fallthrough, or return one of the operators and delimiters ++, --, ), ], or }

source : http://golang.org/doc/go_spec.html#Semicolons

There's a semicolon inserted at the end of this line :

func( y int ) int { return y * 2 }

There are a few cases like that where you need to know this rule because it prevents the formating you'd like to have.

Upvotes: 9

Related Questions