2015-06-19 30 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.

(强调)

相关问题