Nan Xiao
Nan Xiao

Reputation: 17467

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 is compile error:

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

Why does the compiler complain about it?

Upvotes: 2

Views: 3567

Answers (2)

icza
icza

Reputation: 417412

The answer is not simply "because Go doesn't need parentheses"; see that the following example is a 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 my example and yours is that my example only contains the Expression block. Expressions can be parenthesized as you want to (it will not be well formatted, but that is another question).

In your example you specified both the Simple statement and the Expression block. If you put the whole into parentheses, the compiler will try to interpret the whole as the Expression Block to which this does not qualify:

Expression = UnaryExpr | Expression binary_op UnaryExpr .

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

Even j := 9 in itself is not an expression, it is a Short variable declaration. Moreover the simple assignment (e.g. j = 9) is not an expression in Go but a statement (Spec: Assignments). Note that assignment is usually an expression in other languages like C, Java etc.). This is the reason why for example the following code is also invalid:

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

Upvotes: 13

IamNaN
IamNaN

Reputation: 6864

Because that is how the Go syntax defines an if statement.

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

And from 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.

(Emphasis added)

Upvotes: 3

Related Questions