Coding/Learn/rust/loops loop while for
Rust Foundational Course
01.Introduction to Rust & Memory Safety
02.Formatting, Comments & Macros (println!)
03.Variables, Mutability & Shadowing
04.Scalar & Compound Types (Integers, Floats, Tuples, Arrays)
05.Functions, Parameters & Return Expressions
06.Conditionals & If as an Expression
07.Ownership Rules & Move Semantics
08.References & Borrowing (&T)
09.Mutable References (&mut) & Aliasing XOR Mutability
10.Slices & String Types (&str vs String)
11.Loops in Rust (loop, while, for)
12.Pattern Matching with match Expressions
13.Structs, Associated Functions & Methods (impl)
14.Enums & the Option<T> Type (No Null!)
15.Concise Pattern Matching (if let & let else)
16.Vectors & Growable Collections (Vec<T>)
17.Error Handling with Result<T, E> & the ? Operator
18.Traits, Shared Behavior & Generics
19.Closures & Functional Iterators (map, filter, collect)
20.Capstone: High-Performance In-Memory Log Telemetry Engine
Course Certificate0%

Complete all lessons to earn

LearnLoops in Rust (loop, while, for)
11 / 20 0%
Lesson 11 of 20
5 mins read

Loops in Rust (loop, while, for)

PreviousNext Lesson
In Plain English

Rust provides three loop constructs: loop (infinite loop that can return values via break expr), while (condition-based loop), and for (safe iteration over ranges and iterators).

The Mental Model

"loop is a conveyor belt that runs forever until you pull the emergency lever (break value). for is a delivery driver who visits every address on a list in order and stops when the list is done."

Deep Dive: How It Works

Returning Values from loop: break result; terminates loop and evaluates to result.

for in Range: for i in 0..5 iterates 0, 1, 2, 3, 4 (inclusive: 0..=5).

Iterator Safety: for element in &array eliminates index out-of-bounds panics completely.

Syntax Blueprint

let val = loop { if done { break 42; } }; | for i in 1..=3 { ... }

Use loop for retries that return values and for in ranges for clean counting.

PointCore Rules to Remember

Point star
loop Keyword: Infinite loop construct; break expr returns values directly.
Point star
while Loop: Runs as long as condition evaluates to true.
Point star
for..in Iteration: Idiomatic and safe iteration over ranges (0..5) and collections.

Common Beginner Traps & How to Fix Them

Mistake:Using 0..5 expecting it to include 5.

Why it happens: 0..5 is exclusive of the upper bound (yields 0 to 4).

How to fix: Use the inclusive range operator 0..=5 if 5 must be included.

Pro Tip: Label nested loops with single quotes ('outer: loop { break 'outer; }) to exit outer loops cleanly.

Live Interactive Example

Hit Run Code to see it live
Returning Values from Loop and For Range
Rust 1.78 / rustc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Output Console
Click "Run Code" to view the rendered output.
How it works: Demonstrates break returning a value from loop and iterating over 1..=4.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Calculate factorial with a for loop

  • PointCalculate factorial of 5 (1 * 2 * 3 * 4 * 5 = 120).
  • PointInitialize let mut product = 1;
  • PointUse for i in 1..=5 { product *= i; }
  • PointPrint "Factorial: 120".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates