Syntax error: unexpected semicolon or new line waiting}

I have this code example where I define an array, but it does not 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 delete a new line, 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?

+4
source share
2 answers

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

 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) } 
+12
source

When the input is split into tokens, a semicolon is automatically inserted into the token stream at the end of a non-empty line, if the end line token

identifier - integer, floating, 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, a semicolon is inserted at the end of this line:

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

There are several cases where you need to know this rule because it prevents the formation that you would like to have.

+6
source

Source: https://habr.com/ru/post/1400612/


All Articles