语法错误:意外的分号或换行符,期待}

Osc*_*Ryz 7 arrays go

我有这个示例代码,我正在定义一个数组,但它不编译:

$ 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 }
Run Code Online (Sandbox Code Playgroud)

但是,如果我删除换行符,它会起作用:

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

oreyes@OREYES-WIN7 ~/code/go
$ go build a.go
Run Code Online (Sandbox Code Playgroud)

怎么会?

小智 16

只需,在包含数组元素的所有行的末尾添加一个逗号():

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)
}
Run Code Online (Sandbox Code Playgroud)


Den*_*ret 6

当输入被分解为令牌时,如果该行的最终令牌是,则在非空行的末尾自动将分号插入到令牌流中

一个标识符,一个整数,浮点,虚数,字符或字符串文字,其中一个关键字是break,continue,fallthrough,或者返回一个运算符和分隔符++, - ,),]或}

来源:http://golang.org/doc/go_spec.html#Semicolons

在这一行的末尾插入了一个分号:

func( y int ) int { return y * 2 }
Run Code Online (Sandbox Code Playgroud)

在某些情况下,您需要了解此规则,因为它会阻止您希望进行格式化.