How to Make A Range in Rust
In this article, we will learn about making a range in Rust.
Use Range Notation a..b
in Rust
It is possible to iterate through an Iterator
using the for in
construct. One of the simplest methods to generate an iterator is to use the range notation a..b
.
This is one of the most common notations. This produces values ranging from a
(inclusive) to b
(exclusive) in one-step increments.
The range encompasses both the beginning and the end of the time. And, if we want to make the range inclusive of the end, we can use the range syntax a..=b
to do this.
Example:
fn main() {
for i in 1..10 {
if i % 5 == 0 {
println!("hellothere");
} else if i % 2 == 0 {
println!("hello");
} else if i % 4 == 0 {
println!("there");
} else {
println!("{}", i);
}
}
}
Output:
1
hello
3
hello
hellothere
hello
7
hello
9
Here, n
will take the values: 1, 2, ..., 10
in each iteration.
Use Range Notation a..=b
in Rust
Instead, a..=b
can also be used for a range
inclusive on both ends. The above code can also be written as the following.
fn main() {
for i in 1..=10 {
if i % 5 == 0 {
println!("hellothere");
} else if i % 2 == 0 {
println!("hello");
} else if i % 4 == 0 {
println!("there");
} else {
println!("{}", i);
}
}
}
Output:
1
hello
3
hello
hellothere
hello
7
hello
9
hellothere
Here, n
will also take the values: 1, 2, ..., 10
in each iteration.
a..b
as C’s for
Loop in Rust
The a..b
syntax can be used to iterate through a range of numbers, similar to C’s for
loops work.
for i in 0..3 {
println!("{}", i);
}
If we require both the index and the element from an array, the Iterator::enumerate
method is the idiomatic way to accomplish this.
fn main() {
let values = ["rust", "rust1", "rust2"];
for (x, y) in values.iter().enumerate() {
println!("The string for {} is {}", x, y);
}
}
Output:
The string for 0 is rust
The string for 1 is rust1
The string for 2 is rust2