Rust Vectors

🦀 Rust Vectors (Vec<T>)

Vectors are the most commonly used data structure in Rust.

They are growable arrays stored on the heap, perfect when the size of data is not known at compile time.


 1. What Is a Vector?

A Vec<T>:

  • Stores elements of the same type

  • Is dynamic (can grow/shrink)

  • Lives on the heap

  • Follows ownership & borrowing rules


 2. Creating a Vector

▶️ Empty vector

let mut v: Vec<i32> = Vec::new();
v.push(10);
v.push(20);

▶️ Using vec! macro

let v = vec![1, 2, 3, 4];

 3. Adding and Removing Elements

let mut v = vec![10, 20];

v.push(30); // add at end
v.pop(); // remove last element


 4. Accessing Vector Elements

▶️ Using Index (⚠️ Risky)

let v = vec![1, 2, 3];
println!("{}", v[1]);

❌ Panic if index is invalid.


▶️ Using get() (Safe ✅)

match v.get(5) {
Some(value) => println!("{}", value),
None => println!("Index not found"),
}

✔ Preferred way


 5. Iterating Over Vectors

▶️ Read-only iteration

let v = vec![1, 2, 3];

for i in &v {
println!(“{}”, i);
}


▶️ Mutable iteration

let mut v = vec![1, 2, 3];

for i in &mut v {
*i += 1;
}


▶️ Taking ownership (rare)

for i in v {
println!("{}", i);
}
// v not usable here

 6. Vector Length & Capacity

let mut v = Vec::with_capacity(10);
v.push(1);
println!(“{}”, v.len()); // number of elements
println!(“{}”, v.capacity()); // allocated space

✔ Capacity optimization improves performance


 7. Vectors and Ownership

let v1 = vec![1, 2, 3];
let v2 = v1; // ownership moved
// println!(“{:?}”, v1); ❌
println!(“{:?}”, v2);

✔ Avoid move using references:

fn print_vec(v: &Vec<i32>) {
println!("{:?}", v);
}

 8. Vectors of Strings

let mut names = Vec::new();
names.push(String::from("Rust"));
names.push(String::from("Go"));

 9. Removing by Index

let mut v = vec![10, 20, 30];

v.remove(1); // removes 20


 10. Common Vector Methods

Method Purpose
push() Add element
pop() Remove last
get() Safe access
remove() Remove by index
len() Size
is_empty() Check empty
clear() Remove all

 11. Vector vs Array

Feature Array Vector
Size Fixed Dynamic
Memory Stack Heap
Growable
Flexibility Low High

❌ Common Mistakes

  • Using index access blindly

  • Ignoring ownership rules

  • Modifying vector while iterating incorrectly

  • Confusing Vec<T> with &[T]


🧠 Key Takeaways

  • Vec<T> is the go-to collection

  • Use get() for safety

  • Prefer borrowing &Vec<T>

  • Heap allocated, dynamic, fast

  • Ownership rules still apply

You may also like...