Vec methods¶
Level: reference · for working programmers
One line: One page per method on Vec<T> — all 46 that stable Rust 1.98 exposes, plus the IntoIterator impls — each with the signature, what it actually does, the trap it is usually involved in, and a program whose printed output is checked by CI.
These pages are a reference, not a course. If you have not met Vec yet, read The Vec first — it explains the pointer/length/capacity triple that makes half of this list make sense. Come back when you know which method you want and need to know how it behaves at the edges.
Every page has the same shape: a one-line summary, the signature, the stability line, the prose, then a complete runnable program and its verified output. Nothing on any of these pages is hand-typed output — tools/run_examples.py compiles each example, runs it, and fails the build if what the page shows is not what the program printed.
The fences without an answer key were compiled too. run_examples.py reaches examples/*.rs and nothing else, so a hand-authored rust block on a page is a claim no gate was checking — and on a reference page that is a strong claim, because the reader's next move is to paste it. Every such block in this folder was therefore extracted back out of the finished page and compiled on its own:
Four failed. Three were loose statements with no enclosing item, which a reader pasting them would have met as a syntax error; the fourth was the three impl IntoIterator blocks quoted from std, which cannot compile standalone at all and is a text fence now, with a line saying why.
That check belongs to this folder, not to the library. Run over the whole repo it fires on 142 of the 178 pages that carry a Rust fence — four in five — and almost none of them are wrong: a lesson about let opens with let x = 5; on purpose, and wrapping that in an fn main() to satisfy a compiler would make it worse to read. The difference is not syntax but contract. Here a fence is a complete demonstration of one method; on a teaching page it is an illustration of one line. No compiler can see which a page promised.
Most "Vec methods" are not on this list¶
Vec<T> implements Deref<Target = [T]>, so every slice method is reachable on a vector and the compiler inserts the conversion silently. That is where the ones you are most likely to be looking for actually live:
| you probably want | it is a slice method |
|---|---|
| sorting | sort, sort_unstable, sort_by, sort_by_key |
| searching | contains, binary_search, iter().position(…) ↗ |
| the ends | first, last, first_mut, last_mut |
| safe indexing | get, get_mut — and the index may be a range: v.get(1..3) is Some(&v[1..3]), v.get(1..99) is None rather than a clamp or a panic |
| iterating | iter, iter_mut, chunks, windows |
| rearranging | reverse, swap, rotate_left, fill |
| joining | concat, join |
Each of those has a page of its own in the slice methods reference, built to the same promise as this one; arrays and slices is the lesson, and slice ↗ in std is the full list. This list holds only what Vec itself defines — which is, almost exactly, the operations that change the length or the buffer. Anything that works within a fixed length belongs to the slice.
That split is the single most useful thing to know about the type: Vec owns and resizes, [T] is a window on elements that already exist.
The signatures¶
Taken from the rendered documentation of the pinned toolchain, Rust 1.98.0, so they match what you get when you build this repo.
Three notes on reading them.
The allocator parameter. Vec has a second, unstable generic parameter (Vec<T, A>), which appears in some return types here — ignore it; on stable there is only the global allocator.
const fn rarely means what you want. It marks a method that may be called in a const context, which for most of these is not usable in practice: a Vec cannot be dropped at compile time (error[E0493]), so Vec::new() in a static works and almost nothing else does.
T must be Sized. The bound is implicit — it is not written in any signature — so Vec<dyn Debug> fails with error[E0277], and the note points at the struct definition: "required by an implicit Sized bound in Vec". The fix is a layer of indirection, Vec<Box<dyn Debug>>, and it is the same bound behind Vec<[T]> and Vec<str> being rejected.
While you are there: the struct has two fields, buf: RawVec<T, A> and len: usize — the capacity lives inside RawVec, not beside the length. The familiar pointer/length/capacity triple is what a Vec means, not how it is spelled, and std says outright that "the ABI is not stable and Vec makes no guarantees about its memory layout (including the order of fields)", so do not write code that assumes either.
Making one¶
| method | what it does |
|---|---|
new |
Empty, and it has not allocated |
with_capacity |
Empty, but the buffer is already there |
Adding elements¶
| method | what it does |
|---|---|
push |
One on the end — amortised O(1) |
push_mut |
The same, returning a &mut to it |
insert |
One at an index, shifting the rest right |
insert_mut |
The same, returning a &mut to it |
append |
Moves every element of another vector in |
extend_from_slice |
Clones every element of a slice in |
extend_from_within |
Clones a range of this vector onto its own end |
Removing one element¶
| method | what it does |
|---|---|
pop |
The last one, as an Option |
pop_if |
The last one, only if it passes a test |
remove |
By index, preserving order — O(n) |
swap_remove |
By index, not preserving order — O(1) |
Removing many¶
| method | what it does |
|---|---|
truncate |
Keep a prefix, drop the tail |
clear |
Drop everything, keep the buffer |
drain |
Remove a range and hand it to you |
retain |
Keep what a predicate approves, one pass |
retain_mut |
The same, with a predicate that can also edit |
extract_if |
retain's mirror: yields what it removes |
splice |
Replace a range with an iterator of any length |
Removing duplicates¶
All three are consecutive-only — they collapse runs, not sets.
| method | what it does |
|---|---|
dedup |
Runs of equal elements, by PartialEq |
dedup_by |
Runs, by a comparison you write |
dedup_by_key |
Runs, by a key you derive |
Length and shape¶
| method | what it does |
|---|---|
len |
How many elements — not bytes |
is_empty |
len() == 0, spelled so it reads |
resize |
Set the length, padding with clones of a value |
resize_with |
Set the length, padding from a closure |
split_off |
Cut in two at an index, returning the tail |
into_flattened |
Vec<[T; N]> → Vec<T>, free |
Capacity¶
| method | what it does |
|---|---|
capacity |
How many fit before the next reallocation |
reserve |
Room for additional more, with slack |
reserve_exact |
Room for additional more, without slack |
try_reserve |
reserve, returning Err instead of aborting |
try_reserve_exact |
reserve_exact, returning Err |
shrink_to_fit |
Give the unused tail back |
shrink_to |
The same, but never below a floor |
spare_capacity_mut |
The gap, as writable uninitialised memory |
Views and conversions¶
| method | what it does |
|---|---|
as_slice |
Borrow the whole thing as &[T] — free |
as_mut_slice |
The same, writable |
into_boxed_slice |
Consume it into an exactly-sized Box<[T]> |
leak |
Consume it into a &'a mut [T], never freeing |
into_iter |
The three IntoIterator impls, and iter vs into_iter |
Raw parts, and the unsafe corner¶
Five methods where the compiler stops helping. Each page says what the safe alternative is, because there almost always is one.
| method | what it does |
|---|---|
as_ptr |
The buffer address, without the length |
as_mut_ptr |
The same, writable |
set_len |
Set the length field — drops nothing, checks nothing |
into_raw_parts |
Decompose into pointer, length, capacity |
from_raw_parts |
Rebuild from those three numbers |
What is not here¶
24 unstable methods. Vec carries a large nightly surface, most of it the allocator API (new_in, with_capacity_in, from_raw_parts_in, allocator, …) plus push_within_capacity, pop_if's neighbours try_remove and peek_mut, from_fn, into_chunks, into_array, try_with_capacity, split_at_spare_mut, and the fallible shrinks. They are omitted because this reference is pinned to what stable 1.98 will actually compile.
The trait impls, except IntoIterator. Vec also gets Clone, Debug, Hash, Ord, Extend, FromIterator and a long list of From conversions. collect into a Vec covers the one you will use most.
See also¶
- The
Vec— the type itself: three numbers, and how they grow - What a
Vecguarantees — the Guarantees section made runnable, including the layout note quoted above - Arrays and slices — where the other half of the methods live
- Vec of Vecs — the nested case, and when to flatten it
- Collections — the six types a program is made of
Vecin the standard library ↗