2012-03-09 12 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 } 

それは防ぐため、このルールを知っておく必要がある場所というようないくつかの例がありますあなたが持っていたいと書いている。

関連する問題