syntax - Why does adding parentheses in if condition results in compile error? -


the following go code runs ok:

package main  import "fmt"  func main() {     if j := 9; j > 0 {         fmt.println(j)     } } 

but after adding parentheses in condition:

package main  import "fmt"  func main() {     if (j := 9; j > 0) {         fmt.println(j)     } } 

there compile error:

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

why compiler complain it?

the answer not "because go doesn't need parentheses"; see following example valid go syntax:

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

go spec: if statements:

ifstmt = "if" [ simplestmt ";" ] expression block [ "else" ( ifstmt | block ) ] . 

the difference between example , yours example contains expression block. expressions can parenthesized want (it not formatted, question).

in example specified both simple statement , expression block. if put whole parentheses, compiler try interpret whole expression block not qualify:

expression = unaryexpr | expression binary_op unaryexpr . 

j > 0 valid expression, j := 9; j > 0 not valid expression.

even j := 9 in not expression, short variable declaration. simple assignment (e.g. j = 9) not expression in go statement (spec: assignments). note assignment expression in other languages c, java etc.). reason why example following code invalid:

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

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -