Rust Tutorial: Control Flow
if/else expressions, loop, while, for — directing program execution in Rust.
Directing execution
Control flow decides which code runs and how many times.
In Rust, `if` is an *expression* — it returns a value. This is different from most languages and is one of Rust's most elegant features.
What you'll learn in this Rust control flow tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- if and else — No parentheses needed around the condition. Braces are always required.
- else if chains — Chain multiple conditions:
- if as an expression — Rust's if returns a value. Both branches must return the same type.
- loop — `loop` runs forever until `break`. It can also return a value via `break value`.
- while loop — `while` repeats while a condition is true.
- for with a range — `1..=5` is an inclusive range (1 through 5). `1..5` excludes the end.
- for over a collection — `for x in &collection` iterates over references to elements.
- continue — `continue` skips to the next iteration.
Rust Control Flow concepts covered
- Directing execution