Reputation: 3827
How do I initialize a vector from 0
to n
in Rust? Is there another way of doing that than creating an empty vector and invoking push
inside a loop?
I prefer a one-liner.
Upvotes: 18
Views: 8891
Reputation: 11866
Here is how you can do it as a one-liner:
let n = 4;
let v: Vec<i32> = (0..n).collect(); // the last element will be n-1
assert_eq!(v, vec![0, 1, 2, 3]);
let v: Vec<i32> = (0..=n).collect(); // the last element will be n
assert_eq!(v, vec![0, 1, 2, 3, 4]);
Or, alternatively:
let v: Vec<i32> = Vec::from_iter(0..n); // the last element will be n-1
assert_eq!(v, vec![0, 1, 2, 3]);
let v: Vec<i32> = Vec::from_iter(0..=n); // the last element will be n
assert_eq!(v, vec![0, 1, 2, 3, 4]);
Instead of i32
we could use other numeric types like u8
, u16
, i8
, etc. That's because both collect()
and Vec::from_iter
are generic methods.
All those solutions make use of the Range or RangeInclusive structs respectively, both of which implement Iterator. That allows them to easily be converted into a Vec, which is most often done via the collect()
method.
Upvotes: 8
Reputation: 362137
A range can be collected into a vector:
pub fn sequence(n: u32) -> Vec<u32> {
(0..n).collect()
}
Upvotes: 22