ADocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Vec<T> (vector) is a Sized, contiguous, and dynamically growable array type that manages a heap-allocated buffer. It provides indexing, amortized push operations, and guarantees that its elements are stored sequentially in memory, making it highly cache-friendly.
Memory Layout
Under the hood, aVec<T> is represented as a struct containing exactly three machine words:
- Pointer: A non-null pointer (internally represented as
Unique<T>, which wrapsNonNull<T>) to the start of the allocated heap buffer. This strict non-null guarantee enables Rust’s null-pointer optimization, allowing types likeOption<Vec<T>>to have the exact same memory footprint asVec<T>. - Capacity: A
usizerepresenting the total number of elements the buffer can currently hold without triggering a reallocation. - Length: A
usizerepresenting the number of initialized elements currently in the vector. The invariantlen <= capacityis always maintained.
Initialization Syntax
Vectors can be initialized empty, pre-allocated, or populated via macros.Growth and Reallocation Mechanics
When an element is added to aVec<T> and len == capacity, the vector must grow. The standard library handles this by:
- Allocating a new, larger heap buffer (historically doubling the capacity).
- Moving the existing elements from the old buffer to the new buffer.
- Deallocating the old buffer.
Vec::with_capacity bypasses this overhead by satisfying the capacity requirement at instantiation.
Ownership and Memory Management
Vec<T> owns its elements. When a vector goes out of scope, its Drop implementation is triggered. This sequentially calls the Drop trait on all initialized elements (from index 0 to len - 1) and subsequently frees the underlying heap buffer.
Slicing and Deref Coercion
Vec<T> implements both Deref<Target = [T]> and DerefMut. This means a vector automatically coerces to an immutable slice (&[T]) via Deref, or a mutable slice (&mut [T]) via DerefMut, when passed by reference. Slices provide a view into the vector’s contiguous memory without taking ownership.
Access Patterns
Accessing elements requires navigating Rust’s borrowing rules and bounds checking.Iteration Mechanics
Vectors support three primary modes of iteration, directly mapping to Rust’s ownership semantics:Master Rust with Deep Grasping Methodology!Learn More





