Vectors and Strings
Get introduced to Rust vectors and the string types.
Vectors
A vector is a dynamic array. It is a collection included in Rust’s standard library.
Because vectors are a collection in the standard library, they should be declared with the Vec::new()
function:
let v: Vec<i32> = Vec::new();
However, the vec!
macro can also be used to declare and instantiate, exactly as we would do with an array:
let v: Vec<i32> = Vec::new();
Vectors in-depth
Let’s unpack the definition above a little more and differentiate between vectors and arrays.
Arrays are one of the basic data types provided by Rust. Vectors are provided by the standard library.
Therefore, vectors are not in scope when using the following feature:
#![no_std]
However, above and beyond that distinction, vectors are dynamic arrays, meaning that:
- Vectors are declared as generics (such as
vec<T>
). This also means that a vector, like an array, can hold only one type. - Vectors are a particular kind of structs.
- Vectors allocate data on the heap. This is useful to know if we have memory restrictions in an embedded environment.
- We can make vectors grow or shrink in size with specific commands.
Arrays, on the contrary, are not dynamic. We have to declare their size beforehand.
Let’s look at some examples:
let vec1 = vec![1, 2, 3, 4, 5];
let mut vec2: Vec<i32> = Vec::new();
vec2.push(1);
vec2.append(&mut vec![2, 3, 4, 5]);
assert_eq!(vec2, vec1);
Get hands-on with 1400+ tech skills courses.