rust range step
In Rust, the range
function is used to create an iterator over a range of values. By default, it generates a sequence of values from the start to the end (exclusive) with a step size of 1. Here's the syntax:
fn main() {
for i in start..end {
// do something with i
}
}
In this example, start
is the starting value of the range (inclusive), and end
is the ending value of the range (exclusive). The loop will iterate over each value in the range and execute the code block inside the loop.
If you want to change the step size, you can use the step_by
method on the range. Here's an example:
fn main() {
for i in (start..end).step_by(step) {
// do something with i
}
}
In this case, step
represents the desired step size. The loop will iterate over the range with the specified step size.
Alternatively, if you want to create a range and collect it into a vector, you can use the collect
method. Here's an example:
fn main() {
let range: Vec<_> = (start..end).collect();
// use the range vector
}
In this example, the collect
method collects the range into a vector, allowing you to store and manipulate the values as needed.
I hope this information helps! Let me know if you have any further questions.