Expand description
A contiguous growable array type with heap-allocated contents, written
Vec<T>.
Vectors have O(1) indexing, amortized O(1) push (to the end) and O(1) pop (from the end).
Vectors ensure they never allocate more than isize::MAX bytes.
§Examples
You can explicitly create a Vec with Vec::new:
let v: Vec<i32> = Vec::new();…or by using the vec! macro:
let v: Vec<i32> = vec![];
let v = vec![1, 2, 3, 4, 5];
let v = vec![0; 10]; // ten zeroesYou can push values onto the end of a vector (which will grow the vector
as needed):
let mut v = vec![1, 2];
v.push(3);Popping values works in much the same way:
let mut v = vec![1, 2];
let two = v.pop();Vectors also support indexing (through the Index and IndexMut traits):
let mut v = vec![1, 2, 3];
let three = v[2];
v[1] = v[1] + 5;§Memory layout
A Vec conceptually consists of a raw pointer ptr to the start of the allocation, a
length len, a capacity cap, and an allocator alloc.
While the exact fields and their order are not specified, a Vec can be converted to and
from these parts using Vec::into_raw_parts_with_allocator, Vec::from_raw_parts_in,
Vec::into_raw_parts, and Vec::from_raw_parts, as well as their NonNull-based
versions.
The parts of a Vec have the following invariants:
-
If
size_of::<T>()andcapare non-zero, then:ptrmust point to the start of a memory block currently allocated viaalloc.Layout::array::<T>(cap)must fit the memory block ofptr. In particular,size_of::<T>() * capmust be at mostisize::MAX. See the safety documentation ofpointer::offset.
-
If
size_of::<T>()orcapis zero, thenptrmust be any sufficiently aligned non-null pointer.NOTE:
ptrwill not be passed to the allocator for deallocation by the destructor ofVecin this case. Thus, it is unwise to use a pointer acquired from the allocator for this, as overallocated memory may end up being leaked. Useptr::danglinginstead. -
The following must always be satisfied:
lenneeds to be less than or equal tocap.- At
ptr, there are at leastlenvalid values of typeT, laid out contiguously (like an array). These values are considered owned by theVec.
It is sound to create a Vec from parts that satisfy these invariants.
Conversely, the memory backing ptr obtained from Vec::as_mut_ptr or
Vec::into_raw_parts_with_allocator-like methods may be deallocated
using the allocator, with layout Layout::array::<T>(cap), provided
that size_of::<T>() or cap is non-zero.
To automatically handle the case where the allocation is zero-sized,
it is recommended to use Vec::from_raw_parts_in, instead of manually
deallocating.
Structs§
- Drain
- A draining iterator for
Vec<T>. - Extract
If - An iterator which uses a closure to determine if an element should be removed.
- Into
Iter - An iterator that moves out of a vector.
- Splice
- A splicing iterator for
Vec. - Vec
- A contiguous growable array type, written as
Vec<T>, short for ‘vector’. - PeekMut
Experimental - Structure wrapping a mutable reference to the last item in a
Vec.