< All Blog

How to Initialize Vector in Rust

November 12, 2022

In Rust, there are a couple of ways to initialize Vector.


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();
assert_eq!(binaries, [0, 1, 10, 11]);


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);
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.

vec! macro

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);

Use methods that return vector

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]);

Recommended Posts

  1. Tuple with a Single Value in Rust

    November 11, 2022
    In Rust, tuples can be used to have different types of values as a container. Array does not allow you to have different types of elements instead. When Tuple …
  2. Wrapping Integers in Rust

    November 10, 2022
    In Rust, integers can be wrapped to avoid panicking during runtime. Checking operations Let's think the following example. The following source code panicks, b…