闽公网安备 35020302035485号
if (expr) stmt书中的脚注讲到:“The right parenthesis serves only to separate the expression from the statement. The left parenthesis actually has no meaning; it is there only to please the eye, since without it, C would allow unbalanced parentheses.” 大概的意思是说:右侧的括号只用于将表达式与语句分隔开。左括号其实没有实际意义,它只是为了让代码看起来更舒服,因为如果没有左括号,C 语言将出现不匹配的括号。
if (a > b)
c;
如果 if 后需要执行多条语句,则用 block 即 {} 包围。同类的还有 Java 等等。但是工程实践中你会发现,各语言的风格指南中几乎总是希望你加上 {} ——不论是否为单条语句——以避免不必要的阅读上的麻烦。if (a > b) {
c;
}
Rust 的选择要粗暴些,它的 if 条件不使用括号。这一点我们可以从其语法定义中看出:

if xxxx {
}
现在回过头来看为什么 if 后面的条件可以不加小括号?因为其语法定义中没有给 Expression 加括号:)let a = 5;
if (true) {
println!("{a} > 2");
}
可以编译通过。但编译器会警告我们:let a = 5;
if (true,).0 {
println!("{a} > 2");
}
再来想一个问题,语法定义中 if 后的 Expression 自然也包括 BlockExpression ,那是不是可以:let a = 5;
if {true} {
println!("{a} > 2");
}
没错,这样是可以的,只不过是 parentheses 和 braces 的区别:warning: unnecessary braces around `if` condition