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