HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RustVariablesData TypesOperatorsStringsVectors (Vec)Conditions (if / match)Loops (for / while)FunctionsOwnership & Borrowing
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Vector & HashMap
🔁 Condition & Loop
🧩 Function
🔑 Ownership & Borrowing
Rust›Loops (for / while)

Loops (for / while)

Iterating over ranges/collections with for and conditional repetition with while.

Simple enough for a 5-year-old to understand

for (range)

1..n does NOT include n; 1..=n includes n.

Example code
1
fn main() {
2
for i in 1..=3 {
1, 2, 3 (includes =3).
Loop1, 2, 3 (includes =3).
3
println!("{}", i);
4
}
5
}
Loop
💡 Hint: 1..3 → 1,2 (3 excluded). 1..=3 → 1,2,3 (3 included).

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print numbers from 1 to 5 (inclusive) vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

Rust has three loop constructs: for, while, and loop. for operates on iterators, while is condition-dependent, and loop is an unconditional infinite loop that is exited using break.

Rust does not have a classic counter-based for loop. Instead, for always iterates over an iterator; a number range is also an iterator. This makes out-of-bounds errors nearly impossible because counter management is not left to you.

An unusual feature of Rust is that loop can return a value: if you provide a value with break, the loop expression produces that value. This allows you to write code that keeps trying until a result is found very cleanly.

What you will learn

  • Iterating over an iterator with for
  • Writing ranges and inclusive ranges
  • Infinite looping with loop and returning values with break
  • Breaking out of labeled loops
  • How iteration affects ownership

When to use?

Use for when traversing the elements of a container. If you also need the index, the enumerate method provides both the index and the element.

If the exit condition is determined in the middle of the body, starting with loop and using break is more readable than while.

Common mistakes

Wrong

fn main() {
    let numbers = vec![1, 2, 3];
    for n in numbers {
        println!("{}", n);
    }
    println!("{:?}", numbers);
}

Iterating directly transfers the OWNERSHIP of the Vec; numbers cannot be used after the loop and the compiler gives a "borrow of moved value" error. To preserve ownership, iteration must start with a reference.

Correct

fn main() {
    let numbers = vec![1, 2, 3];
    for n in &numbers {
        println!("{}", n);
    }
    println!("{:?}", numbers);
}

Wrong

fn main() {
    for i in 1..5 {
        println!("{}", i);
    }
}

This range does NOT INCLUDE the end value: one, two, three, and four are printed, five is not. There is no error message, just one fewer loop iteration. To include the end value, range syntax with an equals sign is used.

Correct

fn main() {
    for i in 1..=5 {
        println!("{}", i);
    }
}

Wrong

fn main() {
    let mut i = 0;
    while i < 3 {
        println!("{}", i);
    }
}

Since the counter is not incremented, the condition never becomes false and the loop goes on infinitely. Rust cannot catch this error because it is a logic error, not a compilation error. Iterating over a range with for completely eliminates this error.

Correct

fn main() {
    for i in 0..3 {
        println!("{}", i);
    }
}

Frequently asked questions

What do I do if I need the index?

The enumerate method yields an index and element pair at each step. This is safer than maintaining a manual counter because correspondence between the index and element is guaranteed, and there is no risk of forgetting to increment the counter.

What is the difference between loop and while true?

loop tells the compiler that the loop is infinite, so it can return values and flow analysis works better. Writing loop for infinite loops is the idiomatic way in Rust; writing a constantly true condition with while is unnecessary.

Can I break out of a nested loop with a single break?

Yes, in Rust loops can be labeled, and you can break out of the outer loop by specifying the label. This is much more readable than using a flag variable and cleanly solves the situation that requires goto in C.

Summary

for always iterates over an iterator; counter management is not left to you.

The dot-dot range does not include the end value; to include it, an equals sign is added.

Iterating without referencing transfers ownership and the container cannot be used afterwards.

An infinite loop is written with loop, and break can return a value.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code