Conditionals

Ein Großteil der Rust-Syntax wird Ihnen aus C oder C++ bekannt sein:

  • Blocks are delimited by curly braces.
  • Zeilenkommentare beginnen mit //, Blockkommentare werden mit /* ... */ begrenzt
  • Schlüsselwörter (keywords) wie if und while funktionieren gleich.
  • Variablenzuweisung erfolgt mit =, Vergleich erfolgt mit ==.

if expressions

You use if expressions exactly like if statements in other languages:

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

In addition, you can use if as an expression. The last expression of each block becomes the value of the if expression:

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.