Rust Data Structures
Estimated reading: 3 minutes 26 views

🦀 Rust – Vectors: Growable Arrays for Dynamic Data

🧲 Introduction – Why Learn Vectors in Rust?

Unlike arrays, which are fixed in size, vectors (Vec<T>) in Rust are growable, heap-allocated, and extremely useful when dealing with data of unknown or dynamic length. They integrate seamlessly with Rust’s ownership system while providing flexible storage capabilities.

🎯 In this guide, you’ll learn:

  • How to create, modify, and iterate over vectors
  • Key differences between arrays and vectors
  • How ownership, borrowing, and methods work with vectors
  • Real code examples with outputs and explanations

✅ Creating a Vector

🔹 Code Example:

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

🧠 Explanation:

  • vec![...] macro creates a vector with initial elements
  • Stored on the heap, unlike stack-allocated arrays

📤 Output:

[1, 2, 3]

🔨 Creating an Empty Vector and Adding Elements

🔹 Code Example:

fn main() {
    let mut numbers = Vec::new();
    numbers.push(10);
    numbers.push(20);
    println!("{:?}", numbers);
}

🧠 Explanation:

  • Vec::new() creates an empty vector
  • push() appends values to the vector
  • mut keyword is required to mutate the vector

📤 Output:

[10, 20]

🧮 Accessing Elements

🔹 Code Example:

fn main() {
    let data = vec![100, 200, 300];

    println!("First: {}", data[0]);

    match data.get(10) {
        Some(val) => println!("Found: {}", val),
        None => println!("Index out of bounds"),
    }
}

🧠 Explanation:

  • data[0] directly accesses the first element
  • .get(index) safely accesses elements and returns Option<T>

📤 Output:

First: 100
Index out of bounds

🔁 Iterating Over Vectors

🔹 Code Example:

fn main() {
    let langs = vec!["Rust", "Go", "Python"];

    for lang in langs.iter() {
        println!("Language: {}", lang);
    }
}

🧠 Explanation:

  • .iter() returns references to each element
  • Vector is not consumed, can still be used after the loop

📤 Output:

Language: Rust
Language: Go
Language: Python

🔄 Iterating with mut to Modify Values

🔹 Code Example:

fn main() {
    let mut nums = vec![1, 2, 3];

    for n in nums.iter_mut() {
        *n *= 2;
    }

    println!("{:?}", nums);
}

🧠 Explanation:

  • .iter_mut() gives mutable references
  • *n *= 2; dereferences and modifies each value

📤 Output:

[2, 4, 6]

🧩 Removing Elements

🔹 Code Example:

fn main() {
    let mut stack = vec![1, 2, 3];
    stack.pop();
    println!("{:?}", stack);
}

🧠 Explanation:

  • pop() removes the last element and returns it as Option<T>

📤 Output:

[1, 2]

❗ Difference Between Array and Vector

FeatureArray ([T; N])Vector (Vec<T>)
SizeFixed at compile-timeDynamic at runtime
MemoryStackHeap
Growable❌ No✅ Yes
MutabilityOnly if declared mutOnly if declared mut
AccessIndex or .get()Index or .get()

🔒 Ownership and Vectors

Vectors own their elements. When a vector is moved, its contents are moved too.

🔹 Code Example:

fn main() {
    let v1 = vec![String::from("data")];
    let v2 = v1;
    // println!("{:?}", v1); // ❌ Would cause a compile error
    println!("{:?}", v2);
}

📌 Summary – Recap & Next Steps

Vectors in Rust are the go-to tool for working with dynamic lists. They balance flexibility with safety, giving you growable collections without compromising performance.

🔍 Key Takeaways:

  • Use vec![] or Vec::new() to create vectors
  • Vectors store data on the heap and can grow or shrink
  • Use .iter(), .iter_mut(), .get() for safe access
  • Ownership rules apply: vectors move, not copy, by default

⚙️ Up next: Dive into Rust – Tuples to understand how to group mixed types together.


❓FAQs


When should I use a vector over an array in Rust?
✅ Use a vector when the size of your collection can change at runtime. Arrays are fixed in size and can’t grow.


Does accessing an invalid index in a vector crash the program?
✅ Yes if you use direct indexing (v[index]), it panics. Use .get(index) for safe access.


Are vectors thread-safe in Rust?
❌ Not by default. You must wrap vectors in Mutex, Arc, or similar concurrency primitives for thread safety.


Can I store multiple types in a vector?
❌ No, unless you use an enum or trait objects like Vec<Box<dyn Trait>>.


Share Now :

Leave a Reply

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

Share

Rust – Vectors

Or Copy Link

CONTENTS
Scroll to Top