Nan*_*iao 0 syntax syntax-error go
以下Go代码运行正常:
package main
import "fmt"
func main() {
if j := 9; j > 0 {
fmt.Println(j)
}
}
Run Code Online (Sandbox Code Playgroud)
但在条件中添加括号后:
package main
import "fmt"
func main() {
if (j := 9; j > 0) {
fmt.Println(j)
}
}
Run Code Online (Sandbox Code Playgroud)
有编译错误:
.\Hello.go:7: syntax error: unexpected :=, expecting )
.\Hello.go:11: syntax error: unexpected }
Run Code Online (Sandbox Code Playgroud)
为什么编译器会抱怨它?
答案不仅仅是"因为Go不需要括号"; 看到以下示例是有效的Go语法:
j := 9
if (j > 0) {
fmt.Println(j)
}
Run Code Online (Sandbox Code Playgroud)
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
Run Code Online (Sandbox Code Playgroud)
我的示例与您的示例之间的区别在于我的示例仅包含Expression块.表达式可以根据需要加括号(它格式不正确,但这是另一个问题).
在您的示例中,您指定了Simple语句和Expression块.如果将整体放入括号中,编译器将尝试将整体解释为不符合条件的表达式块:
Expression = UnaryExpr | Expression binary_op UnaryExpr .
Run Code Online (Sandbox Code Playgroud)
j > 0是有效的表达式,j := 9; j > 0不是有效的表达式.
即使j := 9本身不是表达式,它也是一个Short变量声明.此外,简单赋值(例如j = 9)不是Go中的表达式而是语句(Spec:Assignments).请注意,赋值通常是其他语言(如C,Java等)的表达式.这就是为什么例如以下代码也无效的原因:
x := 3
y := (x = 4)
Run Code Online (Sandbox Code Playgroud)