0
0
Rustprogramming~5 mins

For loop in Rust

Choose your learning style9 modes available
Introduction

A for loop helps you repeat actions easily without writing the same code many times.

When you want to print numbers from 1 to 10.
When you need to check each item in a list or array.
When you want to add up all values in a collection.
When you want to repeat a task a fixed number of times.
When you want to process each character in a word.
Syntax
Rust
for variable in collection {
    // code to repeat
}

The variable takes each value from the collection one by one.

The collection can be a range, array, vector, or anything you can loop over.

Examples
This prints numbers 1 to 4. The range 1..5 means from 1 up to but not including 5.
Rust
for i in 1..5 {
    println!("{}", i);
}
This goes through each fruit in the array and prints a message.
Rust
let fruits = ["apple", "banana", "cherry"];
for fruit in fruits.iter() {
    println!("I like {}", fruit);
}
This loops over each character in the word "hello" and prints it.
Rust
for c in "hello".chars() {
    println!("{}", c);
}
Sample Program

This program loops over the array numbers and prints each number with a label.

Rust
fn main() {
    let numbers = [10, 20, 30];
    for num in numbers.iter() {
        println!("Number: {}", num);
    }
}
OutputSuccess
Important Notes

Rust's for loop provides each item by value from the collection (copies for Copy types), so you don't need to use indexes.

The range a..b includes a but excludes b. Use a..=b to include b.

Summary

Use a for loop to repeat actions over items in a collection.

The loop variable takes each item one by one.

Ranges and arrays are common collections to loop over.