Skip to main content
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 to let or returnable from a function.
  • Return results from an infinite loop via break value; and check nested loops with labels ('outer).
  • Prefer for..in over 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

  1. 11. if as an expression (goodbye ternary operator)
  2. 22. loop with return value and labels
  3. 33. while conditional vs for..in on range
  4. 44. Expressions vs Statements in functions
  5. 5Practical exercises
  6. 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.