Arrays and Vectors

Introduction

In this lesson, we'll explore arrays and vectors, their properties and usage in Rust.

Key Points

  • Arrays: A collection of elements of the same type.
  • Vectors: A resizable array that stores elements of the same type.

Arrays

An array is a data structure that stores elements of the same type in contiguous memory locations.

#![allow(unused)]
fn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];

println!("Array: {:?}", arr);
}

Accessing Elements of an Array

#![allow(unused)]
fn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];

let first = arr[0];
let last = arr[arr.len() - 1];

println!("First element: {}", first);
println!("Last element: {}", last);
}

Iterating Over an Array

#![allow(unused)]
fn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];

for i in arr.iter() {
    println!("{}", i);
}
}

Common Operations on Arrays

#![allow(unused)]
fn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];

let slice = &arr[1..4];

println!("Slice: {:?}", slice);

let reversed = arr.iter().rev().collect::<Vec<_>>();

println!("Reversed: {:?}", reversed);

let mut doubled = arr.iter().map(|x| x * 2).collect::<Vec<_>>();

println!("Doubled: {:?}", doubled);
}
  • Slicing: Get a pointer to a range of elements in an array.
  • Reverse: Reverse the order of elements in an array.
  • Doubled: Double each element in an array. The map method applies a function to each element in an array and returns a new array with the results. The collect method collects the results into a vector.

Vectors

A vector is a resizable array that stores elements of the same type.

#![allow(unused)]
fn main() {
let mut vec: Vec<i32> = vec![1, 2, 3, 4, 5];

println!("Vector: {:?}", vec);
}

Adding and Removing Elements from a Vector

#![allow(unused)]
fn main() {
let mut vec: Vec<i32> = vec![1, 2, 3, 4, 5];

vec.push(6);
vec.push(7);

println!("Added: {:?}", vec);

vec.pop();

println!("Removed: {:?}", vec);
}
  • Push: Add an element to the end of a vector.
  • Pop: Remove the last element from a vector.

Many other the operations on vectors are similar to those on arrays. See the Rust documentation for more information.

When do we use Arrays vs. Vectors?

  • Arrays are ideal when you know the number of elements at compile time and this number won’t change. For example, storing the days of the week or a fixed set of configuration values. Arrays are allocated on the stack, which is generally faster than heap allocation (used by vectors). The memory footprint is predictable and efficient, as no dynamic resizing is required. An example would be storing a list of months in a year. These values never change.

  • Vectors are better suited for scenarios where the size of the data can change at runtime. If you need to add, remove, or modify the number of elements dynamically, vectors are the go-to choice. Vectors are heap-allocated and can grow or shrink in size as needed. They offer more flexibility compared to arrays and are essential when working with collections where the size is not known upfront. An example would be storing a list of users in a chat application. These values can change at runtime.

Why Arrays and Vectors are important?

Foundational Data Structures

Arrays and vectors are some of the most fundamental data structures in computer science. They provide a way to store and manage collections of data, which is essential in virtually all programs. More complex data structures like matrices, heaps, and even databases often rely on arrays or vectors as their underlying storage mechanism.

Memory Management and Performance

Both arrays and vectors allow for constant-time (O(1)) access to elements via indexing. This makes them highly efficient for tasks where you need to frequently access or modify individual elements.

Conclusion

Arrays and vectors are indispensable in computer science due to their efficiency, simplicity, and versatility. Arrays offer speed and predictability for fixed-size data, while vectors provide the flexibility needed to handle dynamic data sets. Mastery of these structures lays the groundwork for understanding more complex data structures and algorithms, making them a key part of any programmer's toolkit.