Coding/Learn/rust/vectors and collections
Rust Foundational Course
01.Introduction to Rust & Memory Safety
02.Formatting, Comments & Macros (println!)
03.Variables, Mutability & Shadowing
04.Scalar & Compound Types (Integers, Floats, Tuples, Arrays)
05.Functions, Parameters & Return Expressions
06.Conditionals & If as an Expression
07.Ownership Rules & Move Semantics
08.References & Borrowing (&T)
09.Mutable References (&mut) & Aliasing XOR Mutability
10.Slices & String Types (&str vs String)
11.Loops in Rust (loop, while, for)
12.Pattern Matching with match Expressions
13.Structs, Associated Functions & Methods (impl)
14.Enums & the Option<T> Type (No Null!)
15.Concise Pattern Matching (if let & let else)
16.Vectors & Growable Collections (Vec<T>)
17.Error Handling with Result<T, E> & the ? Operator
18.Traits, Shared Behavior & Generics
19.Closures & Functional Iterators (map, filter, collect)
20.Capstone: High-Performance In-Memory Log Telemetry Engine
Course Certificate0%

Complete all lessons to earn

LearnVectors & Growable Collections (Vec<T>)
16 / 20 0%
Lesson 16 of 20
6 mins read

Vectors & Growable Collections (Vec<T>)

PreviousNext Lesson
In Plain English

Vec<T> (vector) is a growable, heap-allocated array that stores elements contiguously. Vectors allow dynamic resizing with .push() and .pop(), safe indexing with .get(), and iteration over elements.

The Mental Model

"If a fixed array [T; N] is a rigid metal filing cabinet with fixed slots, a Vec<T> is an expandable accordion folder that automatically stretches to hold as many documents as you insert."

Deep Dive: How It Works

Creation: Vec::new() or convenient vec![1, 2, 3] macro.

Safe Indexing: v[index] panics on out of bounds. v.get(index) returns Option<&T> safely.

Iteration: for item in &v borrows elements immutably; for item in &mut v allows modification in-place.

Syntax Blueprint

let mut v = vec![10, 20]; v.push(30); let second = v.get(1); // Some(&20)

Vectors manage their own heap buffer, growing capacity automatically as needed.

PointCore Rules to Remember

Point star
Growable Heap Array: Dynamically resizes as elements are added or removed.
Point star
.push() & .pop(): O(1) amortized insertions and removals at the end.
Point star
.get() Method: Returns Option<&T> to safely prevent index out-of-bounds panics.

Common Beginner Traps & How to Fix Them

Mistake:Pushing to a vector while holding a reference to an element.

Why it happens: Pushing can cause reallocation of the entire underlying buffer, invalidating existing pointers. Rust compiler prevents this!

How to fix: Finish using element references before performing mutating pushes.

Pro Tip: Use Vec::with_capacity(n) when the number of elements is known upfront to avoid intermediate reallocations.

Live Interactive Example

Hit Run Code to see it live
Vector Creation, Mutation and Iteration
Rust 1.78 / rustc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Output Console
Click "Run Code" to view the rendered output.
How it works: Demonstrates vec! macro initialization, pushing elements, and safe .get() lookup.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Push items to vector and sum

  • PointInitialize let mut scores = Vec::new();
  • PointPush 40, 50, 60 to scores.
  • PointCalculate sum with let sum: i32 = scores.iter().sum();
  • PointPrint "Total Score: 150".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates