Control Flow
If/Else
Choosing a Value
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.
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}");
}
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
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
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
scorestarts at82.- Rust checks whether
score >= 80. 82 >= 80is true.- The
ifexpression choosespass. - 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.