英文:
syntax error: unexpected semicolon or newline, expecting }
问题
我有一个示例代码,在其中定义了一个数组,但它无法编译:
$ 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: 语法错误: 意外的分号或换行符,期望 }
.\a.go:7: 非声明语句在函数体外
.\a.go:8: 语法错误: 意外的 }
然而,如果我删除换行符,它就可以工作:
$ cat a.go
package f
func t() []int {
arr := [] int {
1,
2 }
return arr
}
oreyes@OREYES-WIN7 ~/code/go
$ go build a.go
为什么会这样?
英文:
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?
答案1
得分: 26
只需在包含数组元素的所有行的末尾加上逗号(,
):
arr := [] func(int) int {
func( x int ) int { return x + 1 },
func( y int ) int { return y * 2 }, // 逗号(以防止自动分号插入)
}
英文:
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)
}
答案2
得分: 8
当输入被分解为标记时,如果行的最后一个标记是标识符、整数、浮点数、虚数、字符或字符串字面量,关键字之一(break、continue、fallthrough或return),或者运算符和分隔符之一(++、--、)、]或}),则自动在标记流的末尾插入一个分号。
这一行的末尾插入了一个分号:
func( y int ) int { return y * 2 }
有一些类似的情况,你需要知道这个规则,因为它会阻止你想要的格式化。
英文:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论