w3resource

Comprehensive Guide to Rust For Loop Syntax and Examples


Understanding the For Loop in Rust Programming

The for loop in Rust is a versatile construct for iterating over collections, ranges, or any iterable types. It is a safe and powerful way to traverse through data while taking advantage of Rust's strict compile-time checks. Rust's for loop abstracts away the complexities of manual indexing, reducing runtime errors and improving code clarity.

This guide will cover the syntax, examples, and in-depth explanations of the for loop, providing a solid understanding for developers working with Rust.


Syntax of for Loop in Rust

The basic syntax of a for loop is as follows:

for variable in iterable {
    // Code block to execute
}

Components:

  • variable: A placeholder for each element in the iterable.
  • iterable: A range, collection, or any iterable object.
  • Body: The block of code executed for each iteration.

Example 1: Iterating Over a Range

Code:

fn main() {
    // Iterate over a range from 1 to 5 (inclusive)
    for number in 1..=5 {
        // Print each number
        println!("Number: {}", number);
    }
}

Explanation

    1. 1..=5:

    • Represents a range from 1 to 5, inclusive (..= means inclusive).
    • If you use 1..5, the range is exclusive of 5.

    2. Loop Variable:

    • number takes on each value in the range, one at a time.

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example 2: Iterating Over an Array

Code:

fn main() {
    // Define an array of strings
    let fruits = ["Apple", "Banana", "Cherry"];

    // Iterate over the array
    for fruit in fruits.iter() {
        // Print each fruit
        println!("Fruit: {}", fruit);
    }
}

Explanation

    1. Array and .iter():

    • fruits is an array. The .iter() method creates an iterator for the array.

    2. Element Access:

    • fruit represents each element of the array during the loop.

Output:

Fruit: Apple
Fruit: Banana
Fruit: Cherry

Example 3: Using an Index with enumerate

Code:

fn main() {
    // Define a vector of numbers
    let numbers = vec![10, 20, 30];

    // Iterate with index and value
    for (index, value) in numbers.iter().enumerate() {
        println!("Index: {}, Value: {}", index, value);
    }
}

Explanation

    1. enumerate:

    • Adds an index to each element during iteration.
    • Returns a tuple (index, value).

    2. Pattern Matching:

    • (index, value) destructures the tuple into its components.

Output:

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30

Example 4: Breaking Out of a for Loop

Code:

fn main() {
    // Iterate over a range
    for number in 1..10 {
        if number == 5 {
            // Exit the loop when number equals 5
            break;
        }
        println!("Number: {}", number);
    }
}

Explanation

    1. Condition:

    • The if statement checks whether number == 5.

    2. Break Statement:

    • Exits the loop before completing all iterations.

Output:

Number: 1
Number: 2
Number: 3
Number: 4

Example 5: Skipping Iterations with continue

Code:

fn main() {
    // Iterate over a range
    for number in 1..6 {
        if number == 3 {
            // Skip the iteration when number equals 3
            continue;
        }
        println!("Number: {}", number);
    }
}

Explanation

    1. continue:

    • Skips the current iteration and moves to the next one.

    2. Result:

    • The number 3 is not printed, as it is skipped.

Output:

Number: 1
Number: 2
Number: 4
Number: 5

Key Features of Rust for Loops

    1. Range Iteration:

    • Simplifies working with numeric sequences.

    2. Collection Traversal:

    • Works seamlessly with arrays, vectors, and other iterable types.

    3. Safety:

    • Eliminates the risk of index out-of-bounds errors.

    4. Flexibility:

    • Works with iterators, making it highly extensible for custom data structures.

Why Use for Loops in Rust?

  • Conciseness:
    • Minimal syntax with no manual indexing.
  • Efficiency:
    • Optimized for performance and memory safety.
  • Extensibility:
    • Combines well with iterators and custom types.

Rust Language Questions, Answers, and Code Snippets Collection.



Follow us on Facebook and Twitter for latest update.