rust init vector with range
To initialize a vector with a range in Rust, you can use the collect
method on an iterator. Here's an example:
let range = 1..=5;
let vector: Vec<_> = range.collect();
In this example, we create a range from 1 to 5 (inclusive) using the ..=
operator. We then call the collect
method on the range, which collects the elements into a Vec<_>
(a vector of inferred type). The resulting vector will contain the values 1, 2, 3, 4, and 5.
If you want to initialize a vector with a range of custom step size, you can use the step_by
method on the range. Here's an example:
let range = (1..=10).step_by(2);
let vector: Vec<_> = range.collect();
In this example, we create a range from 1 to 10 (inclusive) and specify a step size of 2 using the step_by
method. The resulting vector will contain the values 1, 3, 5, 7, and 9.