Conditionals

Much of the Rust syntax will be familiar to you from C, C++ or Java:

  • Blocks are delimited by curly braces.
  • Line comments are started with //, block comments are delimited by /* ... */.
  • Keywords like if and while work the same.
  • Variable assignment is done with =, comparison is done with ==.

if

Rust の 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 5 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.

When if is used in an expression, the expression must have a ; to separate it from the next statement. Remove the ; before println! to see the compiler error.