In Rust if is an expression, so it can produce a value directly into a binding.

Program

Play the program to let a score choose the pass label.

score
if_else.rs
Replay: real traced execution (multi-file project)
fn main() {
    let score = 82;
    let grade = if score >= 80 { "pass" } else { "retry" };
    println!("{grade}");
}
fn main() {
    let score = 60;
    let grade = if score >= 80 { "pass" } else { "retry" };
    println!("{grade}");
}
fn main() {
    let score = 95;
    let grade = if score >= 80 { "pass" } else { "retry" };
    println!("{grade}");
}
  1. score ← 82, grade ← "pass"

    1fn main() {2    let scor→ 82e = 82; //@score=60, 82, 953    let grad→ "pass"e = if scor82e >= 80 { "pass" } else { "retry" };4    println!("{grade}");5}
    outputpass
  1. score ← 60, grade ← "retry"

    1fn main() {2    let scor→ 60e = 60;3    let grad→ "retry"e = if scor60e >= 80 { "pass" } else { "retry" };4    println!("{grade}");5}
    outputretry
  1. score ← 95, grade ← "pass"

    1fn main() {2    let scor→ 95e = 95;3    let grad→ "pass"e = if scor95e >= 80 { "pass" } else { "retry" };4    println!("{grade}");5}
    outputpass

Follow the Branch

  1. score starts at 82.
  2. Rust checks whether score >= 80.
  3. 82 >= 80 is true.
  4. The if expression chooses pass.
  5. The program prints pass. | score | comparison | grade | stdout | | --- | --- | --- | --- | | 60 | false | retry | retry | | 82 | true | pass | pass | | 95 | true | pass | pass |
if expression `if ... else ...` evaluates to a value.
comparison `score >= 80` produces a `bool`.
branch value Both branches must produce the same type.

Exercise: if_else.rs

Reproduce pass for score 82, then use the table to identify the branch for scores 60 and 95.