2015-06-19 56 views
0

以下Go代碼運行正常:爲什麼在if條件中添加括號會導致編譯錯誤?

package main 

import "fmt" 

func main() { 
    if j := 9; j > 0 { 
     fmt.Println(j) 
    } 
} 

但添加在條件括號後:

package main 

import "fmt" 

func main() { 
    if (j := 9; j > 0) { 
     fmt.Println(j) 
    } 
} 

有編譯錯誤:

.\Hello.go:7: syntax error: unexpected :=, expecting) 
.\Hello.go:11: syntax error: unexpected } 

爲什麼編譯器抱怨呢?

+1

爲什麼C編譯器會抱怨,如果你省略括號? – Volker

回答

5

答案不是簡單的 「因爲圍棋不需要括號」;看到下面的例子是一個有效的圍棋語法:

j := 9 
if (j > 0) { 
    fmt.Println(j) 
} 

Go Spec: If statements:

IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" (IfStmt | Block) ] . 

我的例子之間的區別和你的是,我的例子只包含表達塊。可以根據需要將表達式加括號(它不會很好格式化,但這是另一個問題)。

在您的示例中,您同時指定了簡單語句和表達式塊。如果你把整成小括號,編譯器會嘗試將整個解釋爲Expression Block to which this does not qualify

Expression = UnaryExpr | Expression binary_op UnaryExpr . 

j > 0是有效的表達式,j := 9; j > 0不是有效的表達。

即使j := 9本身並不是一個表達式,它是一個Short variable declaration。此外,簡單的賦值(例如j = 9)不是Go中的表達式,而是語句(Spec: Assignments)。請注意,賦值通常是C,Java等其他語言中的表達式)。這就是爲什麼例如下面的代碼也是無效的原因:

x := 3 
y := (x = 4) 
+0

你仍然可以寫'if j:= 9; (j> 0){fmt.Println(j)}'。 –

0

因爲那是Go語法definesif聲明。

IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" (IfStmt | Block) ] .

而且從Effective Go

Parentheses

Go needs fewer parentheses than C and Java: control structures (if, for, switch) do not have parentheses in their syntax.

and

Control structures

The control structures of Go are related to those of C but differ in important ways. There is no do or while loop, only a slightly generalized for; switch is more flexible; if and switch accept an optional initialization statement like that of for; break and continue statements take an optional label to identify what to break or continue; and there are new control structures including a type switch and a multiway communications multiplexer, select. The syntax is also slightly different: there are no parentheses and the bodies must always be brace-delimited.

(強調)

相關問題