dongyihao1099 2015-06-19 03:29
浏览 46
已采纳

如果条件导致编译错误,为什么要加括号?

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?

  • 写回答

2条回答 默认 最新

  • dsxfa26482 2015-06-19 05:36
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角