< All Blog
November 12, 2022
In Rust, there are a couple of ways to initialize Vector
.
Vec::new()
Vec::new()
returns an empty vector. You can initialize a new empty vector and then pushing elements onto it using push()
method.
let mut binaries = Vec::new();
binaries.push(0);
binaries.push(1);
binaries.push(10);
binaries.push(11);
assert_eq!(binaries, [0, 1, 10, 11]);
Vec::with_capaticy()
If you know the capacity beforehand, Vec::with_capacity()
can be used as well to initialize a new vector with the given capacity.
let mut toggle = Vec::with_capacity(2);
toggle.push(true);
toggle.push(false);
assert_eq!(toggle, [true, false]);
However, in most of the cases you might just call vec!
macro instead that is explanied in the next section. That macro internally behaves as if initializing a vector with given capacity.
Rust has vec!
macro, which allows you to initialize vector with values in the first place.
let primes = vec![2, 3, 5, 7];
assert_eq!(primes, [2, 3, 5, 7]);
This macro knows the desirable capacity to pass on initialization. In this case, capacity()
should return 12
.
assert_eq!(hours.len(), 12);
assert_eq!(hours.capacity(), 12);
There are some methods that return vector as well. For example, collect()
can return vector if you define Vec
as a type when calling.
let hours: Vec<u8> = (1..13).collect();
assert_eq!(hours, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);