Lesson 3 of 11
Decisions and loops
Watch a loop repeat and an if expression choose which code runs.
main.rs
fn main() { for n in 1..=3 { if n == 2 { println!("Two!"); } else { println!("{n}"); } }}Program state
- Range
- 1 → 2 → 3
Step 1 of 11
The loop will visit 1, 2, and 3.
What’s happening
A for loop runs its body for each item. The range 1..=3 includes both 1 and 3, so the body runs three times.
An if condition must evaluate to a Boolean. Here == asks whether n equals 2. Rust runs the if block when the answer is true and the else block when it is false.
Read more in The Rust Book