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

时间:2012-03-09 16:24:09

标签: 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 }

但是,如果我删除换行符,则可以使用:

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

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

Howcome?

2 个答案:

答案 0 :(得分:15)

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

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)
}

答案 1 :(得分:6)

  

当输入被分解为标记时,会自动添加分号   如果是,则在非空行的末尾插入令牌流   line的最终标记是

     

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

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

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

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

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

相关问题