Rust Lang

Rust For Loop Range

Loops are significant building constructs in programming that allows us to execute a code block repeatedly. They are essential when handling the data collection, processing large amounts of information, and automating repetitive tasks.

There are primarily three types of loops in programming: for, while, and do-while. Each loop has strengths and weaknesses. Understanding when to use each type is essential to write an efficient and effective code.

For Loop

The “for” loop is among the commonly used loop construct. It is mainly used when you know the number of iterations that you wish to perform.

The common use of a “for” loop is iterating over various collections such as arrays, vectors, and other data types that implement the iterator trait.

This tutorial explores how we can work with the “for” loop construct in the Rust programming language. This teaches us how to iterate over various collections and create ranges using the “for” loop.

For Loop in Rust

As mentioned, we can use the “for” loop in Rust to iterate over a collection or any data type that implements the iterator trait.

The syntax for the “for” loop in Rust is as follows:

for item in collection {
    // action
}

 
In this case, the item variable is assigned to each element of the specified collection on each loop iteration.

The following example shows how to use the “for” loop to the iterator over the items of a Rust vector:

fn main() {
    let vec = vec![1, 2, 3, 4, 5];

    for item in vec.iter() {
        println!("{}", item);
    }
}

 
The previous code prints out each element in the vector on a new line.

Rust For Loop Range Operator

Rust provides us with a range operator which is denoted by two periods (..). This operator allows us to define a range of values. Using the range operator, we can specify the start and end values of the range block (inclusive and exclusive, respectively).

The syntax is as follows:

for num in start..end {
    // action
}

 
The following example shows how we can use the range operator to generate the values from 1 to 5:

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

 
Once we run the previous code, we get the following values:

1
2
3
4

 
As you may notice, the range does not include the end value. This is because the range operator excludes the end value by default. However, we can include the end value using the following operator (..=). This tells the Rust compiler that we want to include the last value in the range:

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

 
In this case, if we run the previous code, it should print the following numbers to the console:

1
2
3
4
5

 

Rust Range with Character Values

We can also use the range operators with letters and characters. An example is as follows:

fn main() {
    for char in 'a'..'e' {
        println!("{}", char);
    }
}

 
Result:

a
b
c
d

 
As you can guess, the previous code prints the characters from A to D.

Specify the Step Value in Range

As you may have noticed, the range value increments by one on each iteration by default. However, we can define a custom step size for the range using the step_by() method.

fn main() {
    for even in (2..=10).step_by(2) {
        println!("{}", even);
    }
}

 
If we run the previous code, we should see the values as follows:

2
4
6
8
10

 
This prints the even numbers 2, 4, 6, 8, and 10 to the console.

Conclusion

This tutorial explored how to use Rust for loop with the range operator. Ranges are a compelling feature that allows us to define a sequence of values without explicitly creating an array or vector.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list