【问题标题】:syntax error: unexpected semicolon or newline, expecting }语法错误:意外的分号或换行符,应为 }
【发布时间】:2012-03-10 00:57:28
【问题描述】:

我有这个示例代码,我在其中定义了一个数组,但它没有编译:

$ 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

怎么会?

【问题讨论】:

    标签: arrays go


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      当输入被分解成标记时,分号会自动 如果 行的最终标记是

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

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

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

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

      在某些情况下,您需要了解此规则,因为它会阻止您想要的格式。

      【讨论】:

        猜你喜欢
        • 2016-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        相关资源
        最近更新 更多