Module 2 · Lesson 1 of 23/24 in the course~15 min
Module lessons (1/2)
if, loop, while, and for..in expressions
Lesson preview5 hands-on exercises readyCourse Rust · Module 2 — Flow Control & Pattern Matching
Use if as an expression, return values from loop with break, loop labels, and safely iterate over range .. / ..=.
What you'll learn in this lesson
- Evaluate
if ... else ...directly as an expression assignable toletor returnable from a function. - Return results from an infinite
loopviabreak value;and check nested loops with labels ('outer). - Prefer
for..inover range and slice to eliminate the risk of off-by-one errors.
Overview
Unlike C or Go where if is just a statement, in Rust if and loop are expressions: they can produce a value as long as all branches return the same static type.
Rust does not have the ? : operator because if { a } else { b } fulfills the same role with superior readability:
Sections covered in this lesson
- 11.
ifas an expression (goodbye ternary operator) - 22.
loopwith return value and labels - 33.
whileconditional vsfor..inon range - 44. Expressions vs Statements in functions
- 5Practical exercises
- 6Check for understanding
Pro Lesson · Module 2 — Flow Control & Pattern Matching
Unlock "if, loop, while, and for..in expressions" and the full Course Rust curriculum
Use `if` as an expression, return values from `loop` with `break`, loop labels, and safely iterate over range `..` / `..=`.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Rust plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.