条件控制

Rust 的许多语法与 C、C++ 和 Java 的语法相似:

  • Blocks are delimited by curly braces.
  • 行内注释以 // 起始,块注释使用 /* ... */ 来界定。
  • ifwhile 等关键词作用与以上语言一致。
  • 变量赋值使用 =,值之间比较使用 ==

if 表达式

if 表达式 的用法与其他语言中的 if 语句完全一样。

fn main() {
    let x = 10;
    if x < 20 {
        println!("small");
    } else if x < 100 {
        println!("biggish");
    } else {
        println!("huge");
    }
}

此外,你还可以将 if 用作一个表达式。每个块的最后一个表达式 将成为 if 表达式的值:

fn main() {
    let x = 10;
    let size = if x < 20 { "small" } else { "large" };
    println!("number size: {}", size);
}
This slide should take about 4 minutes.

Because if is an expression and must have a particular type, both of its branch blocks must have the same type. Show what happens if you add ; after "small" in the second example.

如果在表达式中使用 if,则表达式中必须包含 ; 来将其与下一个语句分隔开。移除 println! 前面的 ; 即可查看编译器错误。