Using “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:
// 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 iterate over the items of a Rust vector:
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 as (..). 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 shown in the following:
// action
}
The following example shows how we can use the range operator to generate the values from 1 to 5:
for num in 1..5 {
println!("{}", num);
}
}
Once we run the previous code, the result is as follows:
2
3
4
As you may notice, the previous 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.
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:
2
3
4
5
Rust Range Operator with Character Values
We can also use the range operators with letters and characters. An example is as shown in the following:
for char in 'a'..'e' {
println!("{}", char);
}
}
Result:
b
c
d
As you can guess, the previous code prints the characters from A to D.
Range Specify Step Value
As you might 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.
for even in (2..=10).step_by(2) {
println!("{}", even);
}
}
If we run the previous code, we should see the values as follows:
4
6
8
10
This prints the even numbers 2, 4, 6, 8, and 10 to the console.
In Rust, we can use the range operator with any data type that implements the PartialOrd trait. Such data types include integers, floats, characters, etc. You can also use the range operator with DateTime types, duration, etc.
Conclusion
This tutorial explored how to use the 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.