5 Arrays and Vectors
Learn how to store multiple values of the same type in arrays and vectors. Understand the difference between arrays and vectors.
Arrays
Arrays in Rust are fixed in size and hold values of the same type. Since the size is known ahead of time, it makes them fast but inflexible.
fn main() {
let arr = [10, 20, 30, 40];
println!("Array: {:?}", arr);
}
The {:?}
syntax is used for a Debug representation of a variable. Using {}
is used for Displaying data.
More often than not, using {:?}
will be your best option.
- Arrays use square brackets:
[1, 2, 3]
- Their size is known at compile time.
- You can’t add or remove elements.
- Mostly used when performance is critical and size is known.
The type of an array is specified as [type; length]
, e.g.
let arr: [i32; 4] = [10, 20, 30, 40];
Vectors
Vectors are like growable arrays. They are much more common in everyday Rust code. To create a vector with known values, use the vec![]
macro. Like an array, they must all be the same type.
fn main() {
let v = vec![1, 2, 3, 4, 5];
println!("Vector: {:?}", v);
}
The type of a vector is specified using Vec<T>
where T
is shorthand for any type.
An empty vector can be created using Vec::new()
or vec![]
. If creating an empty vector, the type must be inferred or made explicit. Vectors also have methods. Two handy ones are .len()
for length, and .is_empty()
(equivalent of .len() == 0
)
fn main() {
let x = Vec::new();
println!("x is empty: {}", x.is_empty());
}
This cannot compile because the type of x
is not known. Rust can infer the type if the vector is used elsewhere where the type is known. To make it compile we must specify the type.
fn main() {
let x: Vec<f64> = Vec::new();
println!("x is empty: {}", x.is_empty());
}
Exercise
- Create an array of 4 integers and print it.
- Create a vector with 5 numbers and print it using
{:?}
. - Compare the length of the array and the vector.
- Bonus: create an empty i32 vector.
Solution
View solution
fn main() {
let arr = [1, 2, 3, 4];
println!("Array: {:?}", arr);
let v = vec![10, 20, 30, 40, 50];
println!("Vector: {:?}", v);
// Bonus:
let v = vec![42_i32; 0];
}