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 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'