2012-03-09 58 views
4

我在那里我定义的数组此示例代码,但它不会编译:语法错误:意外分号或换行,期待}

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

[email protected] ~/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 
} 

[email protected] ~/code/go 
$ go build a.go 

请问?

回答

12

简而言之逗号(,)在包含阵列的元件的所有行的末尾:

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

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 }

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

有在此行的末尾插入一个分号:

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

有少数病例一样,你需要知道这个规则,因为它可以防止格式化你想要的。

相关问题