Chapter 25: Rust Vectors

Rust Vectors (Vec<T>), which are the dynamic, growable version of arrays and one of the most used data structures in almost every real Rust program.

In Rust, when you need a list that can grow, shrink, push/pop elements at runtime — you almost always reach for Vec<T> (pronounced “vector”). It’s like Python’s list, Java’s ArrayList, or C++’s std::vector — but with Rust’s famous memory safety guarantees.

Let me explain Rust Vec like your personal teacher sitting next to you with code open: slowly, step by step, with lots of copy-paste examples you can run right now, Hyderabad-flavored analogies (traffic jam, biryani orders, phone contacts), comparisons, and all the important methods & patterns.

1. What is a Vec<T>? (The Core Idea)

Vec<T> = contiguous growable array stored on the heap.

  • It can change size at runtime (grow with push, shrink with pop, remove, etc.)
  • Elements are all the same type T
  • Internally: pointer + length + capacity (heap-allocated buffer)
  • Type: Vec<T> (no fixed size in the type — unlike [T; N])

Analogy: An array [T; 7] is like a fixed table with exactly 7 chairs — you can’t add more people. A Vec<T> is like a banquet hall in Hyderabad with expandable chairs — you start with some, but you can keep adding guests (push), remove some (pop), and the hall automatically gets bigger when needed.

2. Creating a Vec – All Common Ways

Rust
  • mut required if you plan to change it (push/pop/etc.)
  • vec![1, 2, 3] is shorthand for creating + initializing

3. Basic Operations – Push, Pop, Access

Rust
  • push — adds to end (amortized O(1))
  • pop — removes from end, returns Option<T>
  • Indexing [0] — fast, but panics on invalid index
  • .get(index) — returns Option<&T> (safe)

4. Iterating & Borrowing with Vec

Rust
  • &vec or &temperatures → immutable references (&T)
  • &mut vec → mutable references (&mut T)
  • vec.into_iter() → takes ownership, gives owned T

5. Common Methods You’ll Use Every Day

Rust
  • len() vs capacity() — len = how many elements, capacity = reserved space
  • reserve(n) / with_capacity(n) — avoid reallocations
  • sort(), sort_unstable(), sort_by_key()

6. Vec vs Array vs Slice – Quick Recap

Feature Vec<T> Array [T; N] Slice &[T]
Size Dynamic Fixed compile-time View (dynamic length)
Memory Heap Stack Borrowed
Grow/Shrink Yes No No
Type Vec<i32> [i32; 5] &[i32]
Best for Most real lists Small fixed data Function params, views

7. Real-World Example – Managing a Shopping List

Rust

Teacher Summary & Tips

Rust Vec<T> =

  • Your go-to dynamic array — growable, resizable, heap-allocated
  • Created with Vec::new(), vec![…], collect()
  • Push/pop fast at end, insert/remove slower in middle
  • Borrow with & / &mut — same rules as before
  • Prefer &[T] in function parameters (accepts &Vec<T>, &[T], array slices)
  • Use .reserve() when you know approximate size — big performance win

Practice challenge:

  1. Create Vec<String> of favorite foods → sort alphabetically
  2. Make Vec<i32> of 1..=20 → remove even numbers
  3. Function that takes &[i32] and returns sum + average
  4. Try push 1000 elements → check len vs capacity

Next ready?

  • Slices (&[T]) in much more detail?
  • Iterators on Vec (.map, .filter, .collect, .fold…)?
  • Common patterns with Vec (split, join, dedup, etc.)?
  • Or structs containing Vec + ownership/borrowing?

Just tell me — your Rust class is going strong! 🦀🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *