Struct Vec
struct Vec<T, A: Allocator = crate::alloc::Global> { ... }
A contiguous growable array type, written as Vec<T>, short for 'vector'.
Examples
let mut vec = Vecnew;
vec.push;
vec.push;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
vec = 7;
assert_eq!;
vec.extend;
for x in &vec
assert_eq!;
The [vec!] macro is provided for convenient initialization:
let mut vec1 = vec!;
vec1.push;
let vec2 = Vecfrom;
assert_eq!;
It can also initialize each element of a Vec<T> with a given value.
This may be more efficient than performing allocation and initialization
in separate steps, especially when initializing a vector of zeros:
let vec = vec!;
assert_eq!;
// The following is equivalent, but potentially slower:
let mut vec = Vecwith_capacity;
vec.resize;
assert_eq!;
For more information, see Capacity and Reallocation.
Use a Vec<T> as an efficient stack:
let mut stack = Vecnew;
stack.push;
stack.push;
stack.push;
while let Some = stack.pop
Indexing
The Vec type allows access to values by index, because it implements the
Index trait. An example will be more explicit:
let v = vec!;
println!; // it will display '2'
However be careful: if you try to access an index which isn't in the Vec,
your software will panic! You cannot do this:
let v = vec![0, 2, 4, 6];
println!("{}", v[6]); // it will panic!
Use get and get_mut if you want to check whether the index is in
the Vec.
Slicing
A Vec can be mutable. On the other hand, slices are read-only objects.
To get a [slice][prim@slice], use [&]. Example:
let v = vec!;
read_slice;
// ... and that's all!
// you can also do it like this:
let u: & = &v;
// or like this:
let u: & = &v;
In Rust, it's more common to pass slices as arguments rather than vectors
when you just want to provide read access. The same goes for String and
&str.
Capacity and reallocation
The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector. This is not to be confused with the length of a vector, which specifies the number of actual elements within the vector. If a vector's length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated.
For example, a vector with capacity 10 and length 0 would be an empty vector
with space for 10 more elements. Pushing 10 or fewer elements onto the
vector will not change its capacity or cause reallocation to occur. However,
if the vector's length is increased to 11, it will have to reallocate, which
can be slow. For this reason, it is recommended to use Vec::with_capacity
whenever possible to specify how big the vector is expected to get.
Guarantees
Due to its incredibly fundamental nature, Vec makes a lot of guarantees
about its design. This ensures that it's as low-overhead as possible in
the general case, and can be correctly manipulated in primitive ways
by unsafe code. Note that these guarantees refer to an unqualified Vec<T>.
If additional type parameters are added (e.g., to support custom allocators),
overriding their defaults may change the behavior.
Most fundamentally, Vec is and always will be a (pointer, capacity, length)
triplet. No more, no less. The order of these fields is completely
unspecified, and you should use the appropriate methods to modify these.
The pointer will never be null, so this type is null-pointer-optimized.
However, the pointer might not actually point to allocated memory. In particular,
if you construct a Vec with capacity 0 via Vec::new, [vec![]][vec!],
[Vec::with_capacity(0)]Vec::with_capacity, or by calling shrink_to_fit
on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
types inside a Vec, it will not allocate space for them. Note that in this case
the Vec might not report a capacity of 0. Vec will allocate if and only
if size_of::<T>() * capacity() > 0. In general, Vec's allocation
details are very subtle --- if you intend to allocate memory using a Vec
and use it for something else (either to pass to unsafe code, or to build your
own memory-backed collection), be sure to deallocate this memory by using
from_raw_parts to recover the Vec and then dropping it.
If a Vec has allocated memory, then the memory it points to is on the heap
(as defined by the allocator Rust is configured to use by default), and its
pointer points to len initialized, contiguous elements in order (what
you would see if you coerced it to a slice), followed by capacity - len
logically uninitialized, contiguous elements.
A vector containing the elements 'a' and 'b' with capacity 4 can be
visualized as below. The top part is the Vec struct, it contains a
pointer to the head of the allocation in the heap, length and capacity.
The bottom part is the allocation on the heap, a contiguous memory block.
ptr len capacity
+--------+--------+--------+
| 0x0123 | 2 | 4 |
+--------+--------+--------+
|
v
Heap +--------+--------+--------+--------+
| 'a' | 'b' | uninit | uninit |
+--------+--------+--------+--------+
- uninit represents memory that is not initialized, see
MaybeUninit. - Note: the ABI is not stable and
Vecmakes no guarantees about its memory layout (including the order of fields).
Vec will never perform a "small optimization" where elements are actually
stored on the stack for two reasons:
-
It would make it more difficult for unsafe code to correctly manipulate a
Vec. The contents of aVecwouldn't have a stable address if it were only moved, and it would be more difficult to determine if aVechad actually allocated memory. -
It would penalize the general case, incurring an additional branch on every access.
Vec will never automatically shrink itself, even if completely empty. This
ensures no unnecessary allocations or deallocations occur. Emptying a Vec
and then filling it back up to the same len should incur no calls to
the allocator. If you wish to free up unused memory, use
shrink_to_fit or shrink_to.
push and insert will never (re)allocate if the reported capacity is
sufficient. push and insert will (re)allocate if
len == capacity. That is, the reported capacity is completely
accurate, and can be relied on. It can even be used to manually free the memory
allocated by a Vec if desired. Bulk insertion methods may reallocate, even
when not necessary.
Vec does not guarantee any particular growth strategy when reallocating
when full, nor when reserve is called. The current strategy is basic
and it may prove desirable to use a non-constant growth factor. Whatever
strategy is used will of course guarantee O(1) amortized push.
It is guaranteed, in order to respect the intentions of the programmer, that
all of vec![e_1, e_2, ..., e_n], vec![x; n], and Vec::with_capacity(n) produce a Vec
that requests an allocation of the exact size needed for precisely n elements from the allocator,
and no other size (such as, for example: a size rounded up to the nearest power of 2).
The allocator will return an allocation that is at least as large as requested, but it may be larger.
It is guaranteed that the Vec::capacity method returns a value that is at least the requested capacity
and not more than the allocated capacity.
The method Vec::shrink_to_fit will attempt to discard excess capacity an allocator has given to a Vec.
If len == capacity, then a Vec<T> can be converted
to and from a Box<[T]> without reallocating or moving the elements.
Vec exploits this fact as much as reasonable when implementing common conversions
such as into_boxed_slice.
Vec will not specifically overwrite any data that is removed from it,
but also won't specifically preserve it. Its uninitialized memory is
scratch space that it may use however it wants. It will generally just do
whatever is most efficient or otherwise easy to implement. Do not rely on
removed data to be erased for security purposes. Even if you drop a Vec, its
buffer may simply be reused by another allocation. Even if you zero a Vec's memory
first, that might not actually happen because the optimizer does not consider
this a side-effect that must be preserved. There is one case which we will
not break, however: using unsafe code to write to the excess capacity,
and then increasing the length to match, is always valid.
Currently, Vec does not guarantee the order in which elements are dropped.
The order has changed in the past and may change again.
Implementations
impl<T> Vec<T>
const fn new() -> SelfConstructs a new, empty
Vec<T>.The vector will not allocate until elements are pushed onto it.
Examples
# let mut vec: = Vecnew;const fn with_capacity(capacity: usize) -> SelfConstructs a new, empty
Vec<T>with at least the specified capacity.The vector will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the vector will not allocate.It is important to note that although the returned vector has the minimum capacity specified, the vector will have a zero length. For an explanation of the difference between length and capacity, see Capacity and reallocation.
If it is important to know the exact allocated capacity of a
Vec, always use thecapacitymethod after construction.For
Vec<T>whereTis a zero-sized type, there will be no allocation and the capacity will always beusize::MAX.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = Vecwith_capacity; // The vector contains no items, even though it has capacity for more assert_eq!; assert!; // These are all done without reallocating... for i in 0..10 assert_eq!; assert!; // ...but this may make the vector reallocate vec.push; assert_eq!; assert!; // A vector of a zero-sized type will always over-allocate, since no // allocation is necessary let vec_units = Vec::with_capacity; assert_eq!;fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError>Constructs a new, empty
Vec<T>with at least the specified capacity.The vector will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the vector will not allocate.Errors
Returns an error if the capacity exceeds
isize::MAXbytes, or if the allocator reports allocation failure.unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> SelfCreates a
Vec<T>directly from a pointer, a length, and a capacity.Safety
This is highly unsafe, due to the number of invariants that aren't checked:
- If
Tis not a zero-sized type and the capacity is nonzero,ptrmust have been allocated using the global allocator, such as via thealloc::allocfunction. IfTis a zero-sized type or the capacity is zero,ptrneed only be non-null and aligned. Tneeds to have the same alignment as whatptrwas allocated with, if the pointer is required to be allocated. (Thaving a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy thedeallocrequirement that memory must be allocated and deallocated with the same layout.)- The size of
Ttimes thecapacity(ie. the allocated size in bytes), if nonzero, needs to be the same size as the pointer was allocated with. (Because similar to alignment,deallocmust be called with the same layoutsize.) lengthneeds to be less than or equal tocapacity.- The first
lengthvalues must be properly initialized values of typeT. capacityneeds to be the capacity that the pointer was allocated with, if the pointer is required to be allocated.- The allocated size in bytes must be no larger than
isize::MAX. See the safety documentation ofpointer::offset.
These requirements are always upheld by any
ptrthat has been allocated viaVec<T>. Other allocation sources are allowed if the invariants are upheld.Violating these may cause problems like corrupting the allocator's internal data structures. For example it is normally not safe to build a
Vec<u8>from a pointer to a Cchararray with lengthsize_t, doing so is only safe if the array was initially allocated by aVecorString. It's also not safe to build one from aVec<u16>and its length, because the allocator cares about the alignment, and these two types have different alignments. The buffer was allocated with alignment 2 (foru16), but after turning it into aVec<u8>it'll be deallocated with alignment 1. To avoid these issues, it is often preferable to do casting/transmuting usingslice::from_raw_partsinstead.The ownership of
ptris effectively transferred to theVec<T>which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.Examples
use ptr; let v = vec!; // Deconstruct the vector into parts. let = v.into_raw_parts; unsafeUsing memory that was allocated elsewhere:
use ;- If
unsafe fn from_parts(ptr: NonNull<T>, length: usize, capacity: usize) -> SelfCreates a
Vec<T>directly from aNonNullpointer, a length, and a capacity.Safety
This is highly unsafe, due to the number of invariants that aren't checked:
ptrmust have been allocated using the global allocator, such as via thealloc::allocfunction.Tneeds to have the same alignment as whatptrwas allocated with. (Thaving a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy thedeallocrequirement that memory must be allocated and deallocated with the same layout.)- The size of
Ttimes thecapacity(ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment,deallocmust be called with the same layoutsize.) lengthneeds to be less than or equal tocapacity.- The first
lengthvalues must be properly initialized values of typeT. capacityneeds to be the capacity that the pointer was allocated with.- The allocated size in bytes must be no larger than
isize::MAX. See the safety documentation ofpointer::offset.
These requirements are always upheld by any
ptrthat has been allocated viaVec<T>. Other allocation sources are allowed if the invariants are upheld.Violating these may cause problems like corrupting the allocator's internal data structures. For example it is normally not safe to build a
Vec<u8>from a pointer to a Cchararray with lengthsize_t, doing so is only safe if the array was initially allocated by aVecorString. It's also not safe to build one from aVec<u16>and its length, because the allocator cares about the alignment, and these two types have different alignments. The buffer was allocated with alignment 2 (foru16), but after turning it into aVec<u8>it'll be deallocated with alignment 1. To avoid these issues, it is often preferable to do casting/transmuting usingNonNull::slice_from_raw_partsinstead.The ownership of
ptris effectively transferred to theVec<T>which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.Examples
let v = vec!; // Deconstruct the vector into parts. let = v.into_parts; unsafeUsing memory that was allocated elsewhere:
use ; use NonNull;fn from_fn<F>(length: usize, f: F) -> Self where F: FnMut(usize) -> TCreates a
Vec<T>where each element is produced by callingfwith that element's index while walking forward through theVec<T>.This is essentially the same as writing
vec![f(0), f(1), f(2), …, f(length - 2), f(length - 1)]and is similar to
(0..i).map(f), just forVec<T>s not iterators.If
length == 0, this produces an emptyVec<T>without ever callingf.Example
let vec = Vecfrom_fn; // indexes are: 0 1 2 3 4 assert_eq!; let vec2 = Vecfrom_fn; // indexes are: 0 1 2 3 4 5 6 7 assert_eq!; let bool_vec = Vecfrom_fn; // indexes are: 0 1 2 3 4 assert_eq!;The
Vec<T>is generated in ascending index order, starting from the front and going towards the back, so you can use closures with mutable state:let mut state = 1; let a = Vecfrom_fn; assert_eq!;fn into_raw_parts(self: Self) -> (*mut T, usize, usize)Decomposes a
Vec<T>into its raw components:(pointer, length, capacity).Returns the raw pointer to the underlying data, the length of the vector (in elements), and the allocated capacity of the data (in elements). These are the same arguments in the same order as the arguments to
from_raw_parts.After calling this function, the caller is responsible for the memory previously managed by the
Vec. Most often, one does this by converting the raw pointer, length, and capacity back into aVecwith thefrom_raw_partsfunction; more generally, ifTis non-zero-sized and the capacity is nonzero, one may use any method that callsdeallocwith a layout ofLayout::array::<T>(capacity); ifTis zero-sized or the capacity is zero, nothing needs to be done.Examples
let v: = vec!; let = v.into_raw_parts; let rebuilt = unsafe ; assert_eq!;fn into_parts(self: Self) -> (NonNull<T>, usize, usize)Decomposes a
Vec<T>into its raw components:(NonNull pointer, length, capacity).Returns the
NonNullpointer to the underlying data, the length of the vector (in elements), and the allocated capacity of the data (in elements). These are the same arguments in the same order as the arguments tofrom_parts.After calling this function, the caller is responsible for the memory previously managed by the
Vec. The only way to do this is to convert theNonNullpointer, length, and capacity back into aVecwith thefrom_partsfunction, allowing the destructor to perform the cleanup.Examples
let v: = vec!; let = v.into_parts; let rebuilt = unsafe ; assert_eq!;const fn const_make_global(self: Self) -> &'static [T] where T: FreezeInterns the
Vec<T>, making the underlying memory read-only. This method should be called during compile time. (This is a no-op if called during runtime)This method must be called if the memory used by
Vecneeds to appear in the final values of constants.
impl<T, A: Allocator> Vec<T, A>
fn splice<R, I>(self: &mut Self, range: R, replace_with: I) -> Splice<'_, <I as >::IntoIter, A> where R: RangeBounds<usize>, I: IntoIterator<Item = T>Creates a splicing iterator that replaces the specified range in the vector with the given
replace_withiterator and yields the removed items.replace_withdoes not need to be the same length asrange.rangeis removed even if theSpliceiterator is not consumed before it is dropped.It is unspecified how many elements are removed from the vector if the
Splicevalue is leaked.The input iterator
replace_withis only consumed when theSplicevalue is dropped.This is optimal if:
- The tail (elements in the vector after
range) is empty, - or
replace_withyields fewer or equal elements thanrange's length - or the lower bound of its
size_hint()is exact.
Otherwise, a temporary vector is allocated and the tail is moved twice.
Panics
Panics if the range has
start_bound > end_bound, or, if the range is bounded on either end and past the length of the vector.Examples
let mut v = vec!; let new = ; let u: = v.splice.collect; assert_eq!; assert_eq!;Using
spliceto insert new items into a vector efficiently at a specific position indicated by an empty range:let mut v = vec!; let new = ; v.splice; assert_eq!;- The tail (elements in the vector after
fn extract_if<F, R>(self: &mut Self, range: R, filter: F) -> ExtractIf<'_, T, F, A> where F: FnMut(&mut T) -> bool, R: RangeBounds<usize>Creates an iterator which uses a closure to determine if an element in the range should be removed.
If the closure returns
true, the element is removed from the vector and yielded. If the closure returnsfalse, or panics, the element remains in the vector and will not be yielded.Only elements that fall in the provided range are considered for extraction, but any elements after the range will still have to be moved if any element has been extracted.
If the returned
ExtractIfis not exhausted, e.g. because it is dropped without iterating or the iteration short-circuits, then the remaining elements will be retained. Useextract_if().for_each(drop)if you do not need the returned iterator, orretain_mutwith a negated predicate if you also do not need to restrict the range.Using this method is equivalent to the following code:
# let some_predicate = ; # let mut vec = vec!; # let mut vec2 = vec.clone; # let range = 1..5; let mut i = range.start; let end_items = vec.len - range.end; # let mut extracted = vec!; while i < vec.len - end_items # let extracted2: = vec2.extract_if.collect; # assert_eq!; # assert_eq!;But
extract_ifis easier to use.extract_ifis also more efficient, because it can backshift the elements of the array in bulk.The iterator also lets you mutate the value of each element in the closure, regardless of whether you choose to keep or remove it.
Panics
If
rangeis out of bounds.Examples
Splitting a vector into even and odd values, reusing the original vector:
let mut numbers = vec!; let evens = numbers.extract_if.; let odds = numbers; assert_eq!; assert_eq!;Using the range argument to only process a part of the vector:
let mut items = vec!; let ones = items.extract_if.; assert_eq!; assert_eq!;
impl<T, A: Allocator> Vec<T, A>
const fn new_in(alloc: A) -> SelfConstructs a new, empty
Vec<T, A>.The vector will not allocate until elements are pushed onto it.
Examples
use System; # let mut vec: = Vecnew_in;fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError>Constructs a new, empty
Vec<T, A>with at least the specified capacity with the provided allocator.The vector will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the vector will not allocate.Errors
Returns an error if the capacity exceeds
isize::MAXbytes, or if the allocator reports allocation failure.unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> SelfCreates a
Vec<T, A>directly from a pointer, a length, a capacity, and an allocator.Safety
This is highly unsafe, due to the number of invariants that aren't checked:
ptrmust be currently allocated via the given allocatoralloc.Tneeds to have the same alignment as whatptrwas allocated with. (Thaving a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy thedeallocrequirement that memory must be allocated and deallocated with the same layout.)- The size of
Ttimes thecapacity(ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment,deallocmust be called with the same layoutsize.) lengthneeds to be less than or equal tocapacity.- The first
lengthvalues must be properly initialized values of typeT. capacityneeds to fit the layout size that the pointer was allocated with.- The allocated size in bytes must be no larger than
isize::MAX. See the safety documentation ofpointer::offset.
These requirements are always upheld by any
ptrthat has been allocated viaVec<T, A>. Other allocation sources are allowed if the invariants are upheld.Violating these may cause problems like corrupting the allocator's internal data structures. For example it is not safe to build a
Vec<u8>from a pointer to a Cchararray with lengthsize_t. It's also not safe to build one from aVec<u16>and its length, because the allocator cares about the alignment, and these two types have different alignments. The buffer was allocated with alignment 2 (foru16), but after turning it into aVec<u8>it'll be deallocated with alignment 1.The ownership of
ptris effectively transferred to theVec<T>which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.Examples
use System; use ptr; let mut v = Vecwith_capacity_in; v.push; v.push; v.push; // Deconstruct the vector into parts. let = v.into_raw_parts_with_alloc; unsafeUsing memory that was allocated elsewhere:
use ;unsafe fn from_parts_in(ptr: NonNull<T>, length: usize, capacity: usize, alloc: A) -> SelfCreates a
Vec<T, A>directly from aNonNullpointer, a length, a capacity, and an allocator.Safety
This is highly unsafe, due to the number of invariants that aren't checked:
ptrmust be currently allocated via the given allocatoralloc.Tneeds to have the same alignment as whatptrwas allocated with. (Thaving a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy thedeallocrequirement that memory must be allocated and deallocated with the same layout.)- The size of
Ttimes thecapacity(ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment,deallocmust be called with the same layoutsize.) lengthneeds to be less than or equal tocapacity.- The first
lengthvalues must be properly initialized values of typeT. capacityneeds to fit the layout size that the pointer was allocated with.- The allocated size in bytes must be no larger than
isize::MAX. See the safety documentation ofpointer::offset.
These requirements are always upheld by any
ptrthat has been allocated viaVec<T, A>. Other allocation sources are allowed if the invariants are upheld.Violating these may cause problems like corrupting the allocator's internal data structures. For example it is not safe to build a
Vec<u8>from a pointer to a Cchararray with lengthsize_t. It's also not safe to build one from aVec<u16>and its length, because the allocator cares about the alignment, and these two types have different alignments. The buffer was allocated with alignment 2 (foru16), but after turning it into aVec<u8>it'll be deallocated with alignment 1.The ownership of
ptris effectively transferred to theVec<T>which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.Examples
use System; let mut v = Vecwith_capacity_in; v.push; v.push; v.push; // Deconstruct the vector into parts. let = v.into_parts_with_alloc; unsafeUsing memory that was allocated elsewhere:
use ;fn into_raw_parts_with_alloc(self: Self) -> (*mut T, usize, usize, A)Decomposes a
Vec<T>into its raw components:(pointer, length, capacity, allocator).Returns the raw pointer to the underlying data, the length of the vector (in elements), the allocated capacity of the data (in elements), and the allocator. These are the same arguments in the same order as the arguments to
from_raw_parts_in.After calling this function, the caller is responsible for the memory previously managed by the
Vec. The only way to do this is to convert the raw pointer, length, and capacity back into aVecwith thefrom_raw_parts_infunction, allowing the destructor to perform the cleanup.Examples
use System; let mut v: = Vecnew_in; v.push; v.push; v.push; let = v.into_raw_parts_with_alloc; let rebuilt = unsafe ; assert_eq!;fn into_parts_with_alloc(self: Self) -> (NonNull<T>, usize, usize, A)Decomposes a
Vec<T>into its raw components:(NonNull pointer, length, capacity, allocator).Returns the
NonNullpointer to the underlying data, the length of the vector (in elements), the allocated capacity of the data (in elements), and the allocator. These are the same arguments in the same order as the arguments tofrom_parts_in.After calling this function, the caller is responsible for the memory previously managed by the
Vec. The only way to do this is to convert theNonNullpointer, length, and capacity back into aVecwith thefrom_parts_infunction, allowing the destructor to perform the cleanup.Examples
use System; let mut v: = Vecnew_in; v.push; v.push; v.push; let = v.into_parts_with_alloc; let rebuilt = unsafe ; assert_eq!;const fn capacity(self: &Self) -> usizeReturns the total number of elements the vector can hold without reallocating.
Examples
let mut vec: = Vecwith_capacity; vec.push; assert!;A vector with zero-sized elements will always have a capacity of usize::MAX:
;fn reserve(self: &mut Self, additional: usize)Reserves capacity for at least
additionalmore elements to be inserted in the givenVec<T>. The collection may reserve more space to speculatively avoid frequent reallocations. After callingreserve, capacity will be greater than or equal toself.len() + additional. Does nothing if capacity is already sufficient.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = vec!; vec.reserve; assert!;fn reserve_exact(self: &mut Self, additional: usize)Reserves the minimum capacity for at least
additionalmore elements to be inserted in the givenVec<T>. Unlikereserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After callingreserve_exact, capacity will be greater than or equal toself.len() + additional. Does nothing if the capacity is already sufficient.Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer
reserveif future insertions are expected.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = vec!; vec.reserve_exact; assert!;fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve capacity for at least
additionalmore elements to be inserted in the givenVec<T>. The collection may reserve more space to speculatively avoid frequent reallocations. After callingtry_reserve, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use TryReserveError; # process_data.expect;fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve the minimum capacity for at least
additionalelements to be inserted in the givenVec<T>. Unliketry_reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After callingtry_reserve_exact, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if the capacity is already sufficient.Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer
try_reserveif future insertions are expected.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use TryReserveError; # process_data.expect;fn shrink_to_fit(self: &mut Self)Shrinks the capacity of the vector as much as possible.
The behavior of this method depends on the allocator, which may either shrink the vector in-place or reallocate. The resulting vector might still have some excess capacity, just as is the case for
with_capacity. SeeAllocator::shrinkfor more details.Examples
let mut vec = Vecwith_capacity; vec.extend; assert!; vec.shrink_to_fit; assert!;fn shrink_to(self: &mut Self, min_capacity: usize)Shrinks the capacity of the vector with a lower bound.
The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
Examples
let mut vec = Vecwith_capacity; vec.extend; assert!; vec.shrink_to; assert!; vec.shrink_to; assert!;fn into_boxed_slice(self: Self) -> Box<[T], A>Converts the vector into
Box<[T]>.Before doing the conversion, this method discards excess capacity like
shrink_to_fit.Examples
let v = vec!; let slice = v.into_boxed_slice;Any excess capacity is removed:
let mut vec = Vecwith_capacity; vec.extend; assert!; let slice = vec.into_boxed_slice; assert_eq!;fn truncate(self: &mut Self, len: usize)Shortens the vector, keeping the first
lenelements and dropping the rest.If
lenis greater or equal to the vector's current length, this has no effect.The
drainmethod can emulatetruncate, but causes the excess elements to be returned instead of dropped.Note that this method has no effect on the allocated capacity of the vector.
Examples
Truncating a five element vector to two elements:
let mut vec = vec!; vec.truncate; assert_eq!;No truncation occurs when
lenis greater than the vector's current length:let mut vec = vec!; vec.truncate; assert_eq!;Truncating when
len == 0is equivalent to calling theclearmethod.let mut vec = vec!; vec.truncate; assert_eq!;const fn as_slice(self: &Self) -> &[T]Extracts a slice containing the entire vector.
Equivalent to
&s[..].Examples
use ; let buffer = vec!; sink.write.unwrap;const fn as_mut_slice(self: &mut Self) -> &mut [T]Extracts a mutable slice of the entire vector.
Equivalent to
&mut s[..].Examples
use ; let mut buffer = vec!; repeat.read_exact.unwrap;const fn as_ptr(self: &Self) -> *const TReturns a raw pointer to the vector's buffer, or a dangling raw pointer valid for zero sized reads if the vector didn't allocate.
The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
The caller must also ensure that the memory the pointer (non-transitively) points to is never written to (except inside an
UnsafeCell) using this pointer or any pointer derived from it. If you need to mutate the contents of the slice, useas_mut_ptr.This method guarantees that for the purpose of the aliasing model, this method does not materialize a reference to the underlying slice, and thus the returned pointer will remain valid when mixed with other calls to
as_ptr,as_mut_ptr, andas_non_null. Note that calling other methods that materialize mutable references to the slice, or mutable references to specific elements you are planning on accessing through this pointer, as well as writing to those elements, may still invalidate this pointer. See the second example below for how this guarantee can be used.Examples
let x = vec!; let x_ptr = x.as_ptr; unsafeDue to the aliasing guarantee, the following code is legal:
unsafeconst fn as_mut_ptr(self: &mut Self) -> *mut TReturns a raw mutable pointer to the vector's buffer, or a dangling raw pointer valid for zero sized reads if the vector didn't allocate.
The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
This method guarantees that for the purpose of the aliasing model, this method does not materialize a reference to the underlying slice, and thus the returned pointer will remain valid when mixed with other calls to
as_ptr,as_mut_ptr, andas_non_null. Note that calling other methods that materialize references to the slice, or references to specific elements you are planning on accessing through this pointer, may still invalidate this pointer. See the second example below for how this guarantee can be used.The method also guarantees that, as long as
Tis not zero-sized and the capacity is nonzero, the pointer may be passed intodeallocwith a layout ofLayout::array::<T>(capacity)in order to deallocate the backing memory. If this is done, be careful not to run the destructor of theVec, as dropping it will result in double-frees. Wrapping theVecin aManuallyDropis the typical way to achieve this.Examples
// Allocate vector big enough for 4 elements. let size = 4; let mut x: = Vecwith_capacity; let x_ptr = x.as_mut_ptr; // Initialize elements via raw pointer writes, then set length. unsafe assert_eq!;Due to the aliasing guarantee, the following code is legal:
unsafeDeallocating a vector using
Box(which usesdeallocinternally):use ; let mut v = new; let ptr = v.as_mut_ptr; let capacity = v.capacity; let slice_ptr: *mut = slice_from_raw_parts_mut; drop;const fn as_non_null(self: &mut Self) -> NonNull<T>Returns a
NonNullpointer to the vector's buffer, or a danglingNonNullpointer valid for zero sized reads if the vector didn't allocate.The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
This method guarantees that for the purpose of the aliasing model, this method does not materialize a reference to the underlying slice, and thus the returned pointer will remain valid when mixed with other calls to
as_ptr,as_mut_ptr, andas_non_null. Note that calling other methods that materialize references to the slice, or references to specific elements you are planning on accessing through this pointer, may still invalidate this pointer. See the second example below for how this guarantee can be used.Examples
// Allocate vector big enough for 4 elements. let size = 4; let mut x: = Vecwith_capacity; let x_ptr = x.as_non_null; // Initialize elements via raw pointer writes, then set length. unsafe assert_eq!;Due to the aliasing guarantee, the following code is legal:
unsafefn allocator(self: &Self) -> &AReturns a reference to the underlying allocator.
unsafe fn set_len(self: &mut Self, new_len: usize)Forces the length of the vector to
new_len.This is a low-level operation that maintains none of the normal invariants of the type. Normally changing the length of a vector is done using one of the safe operations instead, such as
truncate,resize,extend, orclear.Safety
new_lenmust be less than or equal tocapacity().- The elements at
old_len..new_lenmust be initialized.
Examples
See
spare_capacity_mut()for an example with safe initialization of capacity elements and use of this method.set_len()can be useful for situations in which the vector is serving as a buffer for other code, particularly over FFI:# #![allow(dead_code)] # // This is just a minimal skeleton for the doc example; # // don't use this as a starting point for a real library. # pub struct StreamWrapper { strm: *mut std::ffi::c_void } # const Z_OK: i32 = 0; # unsafe extern "C" { # fn deflateGetDictionary( # strm: *mut std::ffi::c_void, # dictionary: *mut u8, # dictLength: *mut usize, # ) -> i32; # } # impl StreamWrapper { pub fn get_dictionary(&self) -> Option<Vec<u8>> { // Per the FFI method's docs, "32768 bytes is always enough". let mut dict = Vec::with_capacity(32_768); let mut dict_length = 0; // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that: // 1. `dict_length` elements were initialized. // 2. `dict_length` <= the capacity (32_768) // which makes `set_len` safe to call. unsafe { // Make the FFI call... let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length); if r == Z_OK { // ...and update the length to what was initialized. dict.set_len(dict_length); Some(dict) } else { None } } } # }While the following example is sound, there is a memory leak since the inner vectors were not freed prior to the
set_lencall:let mut vec = vec!; // SAFETY: // 1. `old_len..0` is empty so no elements need to be initialized. // 2. `0 <= capacity` always holds whatever `capacity` is. unsafeNormally, here, one would use
clearinstead to correctly drop the contents and thus not leak memory.fn swap_remove(self: &mut Self, index: usize) -> TRemoves an element from the vector and returns it.
The removed element is replaced by the last element of the vector.
This does not preserve ordering of the remaining elements, but is O(1). If you need to preserve the element order, use
removeinstead.Panics
Panics if
indexis out of bounds.Examples
let mut v = vec!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn insert(self: &mut Self, index: usize, element: T)Inserts an element at position
indexwithin the vector, shifting all elements after it to the right.Panics
Panics if
index > len.Examples
let mut vec = vec!; vec.insert; assert_eq!; vec.insert; assert_eq!;Time complexity
Takes O(
Vec::len) time. All items after the insertion index must be shifted to the right. In the worst case, all elements are shifted when the insertion index is 0.fn insert_mut(self: &mut Self, index: usize, element: T) -> &mut TInserts an element at position
indexwithin the vector, shifting all elements after it to the right, and returning a reference to the new element.Panics
Panics if
index > len.Examples
let mut vec = vec!; let x = vec.insert_mut; *x += 1; assert_eq!;Time complexity
Takes O(
Vec::len) time. All items after the insertion index must be shifted to the right. In the worst case, all elements are shifted when the insertion index is 0.fn remove(self: &mut Self, index: usize) -> TRemoves and returns the element at position
indexwithin the vector, shifting all elements after it to the left.Note: Because this shifts over the remaining elements, it has a worst-case performance of O(n). If you don't need the order of elements to be preserved, use
swap_removeinstead. If you'd like to remove elements from the beginning of theVec, consider usingVecDeque::pop_frontinstead.Panics
Panics if
indexis out of bounds.Examples
let mut v = vec!; assert_eq!; assert_eq!;fn try_remove(self: &mut Self, index: usize) -> Option<T>Remove and return the element at position
indexwithin the vector, shifting all elements after it to the left, orNoneif it does not exist.Note: Because this shifts over the remaining elements, it has a worst-case performance of O(n). If you'd like to remove elements from the beginning of the
Vec, consider usingVecDeque::pop_frontinstead.Examples
let mut v = vec!; assert_eq!; assert_eq!;fn retain<F>(self: &mut Self, f: F) where F: FnMut(&T) -> boolRetains only the elements specified by the predicate.
In other words, remove all elements
efor whichf(&e)returnsfalse. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.Examples
let mut vec = vec!; vec.retain; assert_eq!;Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.
let mut vec = vec!; let keep = ; let mut iter = keep.iter; vec.retain; assert_eq!;fn retain_mut<F>(self: &mut Self, f: F) where F: FnMut(&mut T) -> boolRetains only the elements specified by the predicate, passing a mutable reference to it.
In other words, remove all elements
esuch thatf(&mut e)returnsfalse. This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.Examples
let mut vec = vec!; vec.retain_mut; assert_eq!;fn dedup_by_key<F, K>(self: &mut Self, key: F) where F: FnMut(&mut T) -> K, K: PartialEqRemoves all but the first of consecutive elements in the vector that resolve to the same key.
If the vector is sorted, this removes all duplicates.
Examples
let mut vec = vec!; vec.dedup_by_key; assert_eq!;fn dedup_by<F>(self: &mut Self, same_bucket: F) where F: FnMut(&mut T, &mut T) -> boolRemoves all but the first of consecutive elements in the vector satisfying a given equality relation.
The
same_bucketfunction is passed references to two elements from the vector and must determine if the elements compare equal. The elements are passed in opposite order from their order in the slice, so ifsame_bucket(a, b)returnstrue,ais removed.If the vector is sorted, this removes all duplicates.
Examples
let mut vec = vec!; vec.dedup_by; assert_eq!;fn push_within_capacity(self: &mut Self, value: T) -> Result<&mut T, T>Appends an element and returns a reference to it if there is sufficient spare capacity, otherwise an error is returned with the element.
Unlike
pushthis method will not reallocate when there's insufficient capacity. The caller should usereserveortry_reserveto ensure that there is enough capacity.Examples
A manual, panic-free alternative to [
FromIterator]:use TryReserveError; assert_eq!;Time complexity
Takes O(1) time.
fn pop(self: &mut Self) -> Option<T>Removes the last element from a vector and returns it, or
Noneif it is empty.If you'd like to pop the first element, consider using
VecDeque::pop_frontinstead.Examples
let mut vec = vec!; assert_eq!; assert_eq!;Time complexity
Takes O(1) time.
fn pop_if<impl FnOnce(&mut T) -> bool: FnOnce(&mut T) -> bool>(self: &mut Self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T>Removes and returns the last element from a vector if the predicate returns
true, orNoneif the predicate returns false or the vector is empty (the predicate will not be called in that case).Examples
let mut vec = vec!; let pred = ; assert_eq!; assert_eq!; assert_eq!;fn peek_mut(self: &mut Self) -> Option<PeekMut<'_, T, A>>Returns a mutable reference to the last item in the vector, or
Noneif it is empty.Examples
Basic usage:
let mut vec = Vecnew; assert!; vec.push; vec.push; vec.push; assert_eq!; if let Some = vec.peek_mut assert_eq!;fn append(self: &mut Self, other: &mut Self)Moves all the elements of
otherintoself, leavingotherempty.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = vec!; let mut vec2 = vec!; vec.append; assert_eq!; assert_eq!;fn drain<R>(self: &mut Self, range: R) -> Drain<'_, T, A> where R: RangeBounds<usize>Removes the subslice indicated by the given range from the vector, returning a double-ended iterator over the removed subslice.
If the iterator is dropped before being fully consumed, it drops the remaining removed elements.
The returned iterator keeps a mutable borrow on the vector to optimize its implementation.
Panics
Panics if the range has
start_bound > end_bound, or, if the range is bounded on either end and past the length of the vector.Leaking
If the returned iterator goes out of scope without being dropped (due to
mem::forget, for example), the vector may have lost and leaked elements arbitrarily, including elements outside the range.Examples
let mut v = vec!; let u: = v.drain.collect; assert_eq!; assert_eq!; // A full range clears the vector, like `clear()` does v.drain; assert_eq!;fn clear(self: &mut Self)Clears the vector, removing all values.
Note that this method has no effect on the allocated capacity of the vector.
Examples
let mut v = vec!; v.clear; assert!;const fn len(self: &Self) -> usizeReturns the number of elements in the vector, also referred to as its 'length'.
Examples
let a = vec!; assert_eq!;const fn is_empty(self: &Self) -> boolReturns
trueif the vector contains no elements.Examples
let mut v = Vecnew; assert!; v.push; assert!;fn split_off(self: &mut Self, at: usize) -> Self where A: CloneSplits the collection into two at the given index.
Returns a newly allocated vector containing the elements in the range
[at, len). After the call, the original vector will be left containing the elements[0, at)with its previous capacity unchanged.- If you want to take ownership of the entire contents and capacity of
the vector, see
mem::takeormem::replace. - If you don't need the returned vector at all, see
Vec::truncate. - If you want to take ownership of an arbitrary subslice, or you don't
necessarily want to store the removed items in a vector, see
Vec::drain.
Panics
Panics if
at > len.Examples
let mut vec = vec!; let vec2 = vec.split_off; assert_eq!; assert_eq!;- If you want to take ownership of the entire contents and capacity of
the vector, see
fn resize_with<F>(self: &mut Self, new_len: usize, f: F) where F: FnMut() -> TResizes the
Vecin-place so thatlenis equal tonew_len.If
new_lenis greater thanlen, theVecis extended by the difference, with each additional slot filled with the result of calling the closuref. The return values fromfwill end up in theVecin the order they have been generated.If
new_lenis less thanlen, theVecis simply truncated.This method uses a closure to create new values on every push. If you'd rather
Clonea given value, useVec::resize. If you want to use theDefaulttrait to generate values, you can passDefault::defaultas the second argument.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = vec!; vec.resize_with; assert_eq!; let mut vec = vec!; let mut p = 1; vec.resize_with; assert_eq!;fn leak<'a>(self: Self) -> &'a mut [T] where A: 'aConsumes and leaks the
Vec, returning a mutable reference to the contents,&'a mut [T].Note that the type
Tmust outlive the chosen lifetime'a. If the type has only static references, or none at all, then this may be chosen to be'static.As of Rust 1.57, this method does not reallocate or shrink the
Vec, so the leaked allocation may include unused capacity that is not part of the returned slice.This function is mainly useful for data that lives for the remainder of the program's life. Dropping the returned reference will cause a memory leak.
Examples
Simple usage:
let x = vec!; let static_ref: &'static mut = x.leak; static_ref += 1; assert_eq!; # // FIXME(https://github.com/rust-lang/miri/issues/3670): # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. # drop;fn spare_capacity_mut(self: &mut Self) -> &mut [MaybeUninit<T>]Returns the remaining spare capacity of the vector as a slice of
MaybeUninit<T>.The returned slice can be used to fill the vector with data (e.g. by reading from a file) before marking the data as initialized using the
set_lenmethod.Examples
// Allocate vector big enough for 10 elements. let mut v = Vecwith_capacity; // Fill in the first 3 elements. let uninit = v.spare_capacity_mut; uninit.write; uninit.write; uninit.write; // Mark the first 3 elements of the vector as being initialized. unsafe assert_eq!;fn split_at_spare_mut(self: &mut Self) -> (&mut [T], &mut [MaybeUninit<T>])Returns vector content as a slice of
T, along with the remaining spare capacity of the vector as a slice ofMaybeUninit<T>.The returned spare capacity slice can be used to fill the vector with data (e.g. by reading from a file) before marking the data as initialized using the
set_lenmethod.Note that this is a low-level API, which should be used with care for optimization purposes. If you need to append data to a
Vecyou can usepush,extend,extend_from_slice,extend_from_within,insert,append,resizeorresize_with, depending on your exact needs.Examples
let mut v = vec!; // Reserve additional space big enough for 10 elements. v.reserve; let = v.split_at_spare_mut; let sum = init.iter.copied.; // Fill in the next 4 elements. uninit.write; uninit.write; uninit.write; uninit.write; // Mark the 4 elements of the vector as being initialized. unsafe assert_eq!;fn into_chunks<N: usize>(self: Self) -> Vec<[T; N], A>Groups every
Nelements in theVec<T>into chunks to produce aVec<[T; N]>, dropping elements in the remainder.Nmust be greater than zero.If the capacity is not a multiple of the chunk size, the buffer will shrink down to the nearest multiple with a reallocation or deallocation.
This function can be used to reverse
Vec::into_flattened.Examples
let vec = vec!; assert_eq!; let vec = vec!; let chunks: = vec.into_chunks; assert!; let flat = vec!; let reshaped: = flat.into_chunks.into_chunks.into_chunks; assert_eq!;fn recycle<U>(self: Self) -> Vec<U, A> where U: Recyclable<T>This clears out this
Vecand recycles the allocation into a newVec. The item type of the resultingVecneeds to have the same size and alignment as the item type of the originalVec.Examples
let a: = vec!; let capacity = a.capacity; let addr = a.as_ptr.addr; let b: = a.recycle; assert_eq!; assert_eq!; assert_eq!;The
Recyclablebound prevents this method from being called whenTandUhave different sizes; e.g.:#![feature(vec_recycle, transmutability)] let vec: Vec<[u8; 2]> = Vec::new(); let _: Vec<[u8; 1]> = vec.recycle();...or different alignments:
#![feature(vec_recycle, transmutability)] let vec: Vec<[u16; 0]> = Vec::new(); let _: Vec<[u8; 0]> = vec.recycle();However, due to temporary implementation limitations of
Recyclable, this method is not yet callable whenTorUare slices, trait objects, or other exotic types; e.g.:#![feature(vec_recycle, transmutability)] # let inputs = ["a b c", "d e f"]; # fn process(_: &[&str]) {} let mut storage: Vec<&[&str]> = Vec::new(); for input in inputs { let mut buffer: Vec<&str> = storage.recycle(); buffer.extend(input.split(" ")); process(&buffer); storage = buffer.recycle(); }
impl<T, A: Allocator, N: usize> Vec<[T; N], A>
fn into_flattened(self: Self) -> Vec<T, A>Takes a
Vec<[T; N]>and flattens it into aVec<T>.Panics
Panics if the length of the resulting vector would overflow a
usize.This is only possible when flattening a vector of arrays of zero-sized types, and thus tends to be irrelevant in practice. If
size_of::<T>() > 0, this will never panic.Examples
let mut vec = vec!; assert_eq!; let mut flattened = vec.into_flattened; assert_eq!;
impl<T, A: ~const Allocator> Vec<T, A>
const fn with_capacity_in(capacity: usize, alloc: A) -> SelfConstructs a new, empty
Vec<T, A>with at least the specified capacity with the provided allocator.The vector will be able to hold at least
capacityelements without reallocating. This method is allowed to allocate for more elements thancapacity. Ifcapacityis zero, the vector will not allocate.It is important to note that although the returned vector has the minimum capacity specified, the vector will have a zero length. For an explanation of the difference between length and capacity, see Capacity and reallocation.
If it is important to know the exact allocated capacity of a
Vec, always use thecapacitymethod after construction.For
Vec<T, A>whereTis a zero-sized type, there will be no allocation and the capacity will always beusize::MAX.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
use System; let mut vec = Vecwith_capacity_in; // The vector contains no items, even though it has capacity for more assert_eq!; assert!; // These are all done without reallocating... for i in 0..10 assert_eq!; assert!; // ...but this may make the vector reallocate vec.push; assert_eq!; assert!; // A vector of a zero-sized type will always over-allocate, since no // allocation is necessary let vec_units = Vec::with_capacity_in; assert_eq!;const fn push(self: &mut Self, value: T)Appends an element to the back of a collection.
Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = vec!; vec.push; assert_eq!;Time complexity
Takes amortized O(1) time. If the vector's length would exceed its capacity after the push, O(capacity) time is taken to copy the vector's elements to a larger allocation. This expensive operation is offset by the capacity O(1) insertions it allows.
const fn push_mut(self: &mut Self, value: T) -> &mut TAppends an element to the back of a collection, returning a reference to it.
Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = vec!; let last = vec.push_mut; assert_eq!; assert_eq!; let last = vec.push_mut; *last += 1; assert_eq!;Time complexity
Takes amortized O(1) time. If the vector's length would exceed its capacity after the push, O(capacity) time is taken to copy the vector's elements to a larger allocation. This expensive operation is offset by the capacity O(1) insertions it allows.
impl<T: Clone, A: Allocator> Vec<T, A>
fn resize(self: &mut Self, new_len: usize, value: T)Resizes the
Vecin-place so thatlenis equal tonew_len.If
new_lenis greater thanlen, theVecis extended by the difference, with each additional slot filled withvalue. Ifnew_lenis less thanlen, theVecis simply truncated.This method requires
Tto implementClone, in order to be able to clone the passed value. If you need more flexibility (or want to rely onDefaultinstead ofClone), useVec::resize_with. If you only need to resize to a smaller size, useVec::truncate.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = vec!; vec.resize; assert_eq!; let mut vec = vec!; vec.resize; assert_eq!;fn extend_from_slice(self: &mut Self, other: &[T])Clones and appends all elements in a slice to the
Vec.Iterates over the slice
other, clones each element, and then appends it to thisVec. Theotherslice is traversed in-order.Note that this function is the same as
extend, except that it also works with slice elements that are Clone but not Copy. If Rust gets specialization this function may be deprecated.Panics
Panics if the new capacity exceeds
isize::MAXbytes.Examples
let mut vec = vec!; vec.extend_from_slice; assert_eq!;fn extend_from_within<R>(self: &mut Self, src: R) where R: RangeBounds<usize>Given a range
src, clones a slice of elements in that range and appends it to the end.srcmust be a range that can form a valid subslice of theVec.Panics
Panics if starting index is greater than the end index, if the index is greater than the length of the vector, or if the new capacity exceeds
isize::MAXbytes.Examples
let mut characters = vec!; characters.extend_from_within; assert_eq!; let mut numbers = vec!; numbers.extend_from_within; assert_eq!; let mut strings = vec!; strings.extend_from_within; assert_eq!;
impl<T: PartialEq, A: Allocator> Vec<T, A>
fn dedup(self: &mut Self)Removes consecutive repeated elements in the vector according to the
PartialEqtrait implementation.If the vector is sorted, this removes all duplicates.
Examples
let mut vec = vec!; vec.dedup; assert_eq!;
impl From for Vec<u8>
fn from(s: &str) -> Vec<u8>Allocates a
Vec<u8>and fills it with a UTF-8 string.Examples
assert_eq!;
impl From for crate::vec::Vec<u8>
fn from(s: ByteString) -> Self
impl From for crate::vec::Vec<u8>
impl From for crate::vec::Vec<u8>
impl<'a> PartialEq for crate::vec::Vec<u8>
fn eq(self: &Self, other: &ByteStr) -> bool
impl<'a> PartialEq for crate::vec::Vec<u8>
fn eq(self: &Self, other: &ByteString) -> bool
impl<'a, T> From for Vec<T>
fn from(s: Cow<'a, [T]>) -> Vec<T>Converts a clone-on-write slice into a vector.
If
salready owns aVec<T>, it will be returned directly. Ifsis borrowing a slice, a newVec<T>will be allocated and filled by clonings's items into it.Examples
# use Cow; let o: = Owned; let b: = Borrowed; assert_eq!;
impl<'a, T: Copy + 'a, A: Allocator> Extend for Vec<T, A>
fn extend<I: IntoIterator<Item = &'a T>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, item: &'a T)fn extend_reserve(self: &mut Self, additional: usize)
impl<P, T> Receiver for Vec<T, A>
impl<T> Any for Vec<T, A>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Vec<T, A>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Vec<T, A>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for Vec<T, A>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> Default for Vec<T>
fn default() -> Vec<T>Creates an empty
Vec<T>.The vector will not allocate until elements are pushed onto it.
impl<T> From for Vec<T, A>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> FromIterator for Vec<T>
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T>
impl<T> ToOwned for Vec<T, A>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, A> Freeze for Vec<T, A>
impl<T, A> RefUnwindSafe for Vec<T, A>
impl<T, A> Send for Vec<T, A>
impl<T, A> Sync for Vec<T, A>
impl<T, A> Unpin for Vec<T, A>
impl<T, A> UnwindSafe for Vec<T, A>
impl<T, A1, A2> PartialOrd for Vec<T, A1>
fn partial_cmp(self: &Self, other: &Vec<T, A2>) -> Option<Ordering>
impl<T, A: Allocator> AsMut for Vec<T, A>
fn as_mut(self: &mut Self) -> &mut Vec<T, A>
impl<T, A: Allocator> AsMut for Vec<T, A>
fn as_mut(self: &mut Self) -> &mut [T]
impl<T, A: Allocator> AsRef for Vec<T, A>
fn as_ref(self: &Self) -> &Vec<T, A>
impl<T, A: Allocator> AsRef for Vec<T, A>
fn as_ref(self: &Self) -> &[T]
impl<T, A: Allocator> Borrow for crate::vec::Vec<T, A>
fn borrow(self: &Self) -> &[T]
impl<T, A: Allocator> BorrowMut for crate::vec::Vec<T, A>
fn borrow_mut(self: &mut Self) -> &mut [T]
impl<T, A: Allocator> Deref for Vec<T, A>
fn deref(self: &Self) -> &[T]
impl<T, A: Allocator> DerefMut for Vec<T, A>
fn deref_mut(self: &mut Self) -> &mut [T]
impl<T, A: Allocator> DerefPure for Vec<T, A>
impl<T, A: Allocator> Drop for Vec<T, A>
fn drop(self: &mut Self)
impl<T, A: Allocator> Extend for Vec<T, A>
fn extend<I: IntoIterator<Item = T>>(self: &mut Self, iter: I)fn extend_one(self: &mut Self, item: T)fn extend_reserve(self: &mut Self, additional: usize)
impl<T, A: Allocator> From for Vec<T, A>
fn from(s: Box<[T], A>) -> SelfConverts a boxed slice into a vector by transferring ownership of the existing heap allocation.
Examples
let b: = vec!.into_boxed_slice; assert_eq!;
impl<T, A: Allocator> From for crate::vec::Vec<T, A>
fn from(heap: BinaryHeap<T, A>) -> Vec<T, A>Converts a
BinaryHeap<T>into aVec<T>.This conversion requires no data movement or allocation, and has constant time complexity.
impl<T, A: Allocator> From for crate::vec::Vec<T, A>
fn from(other: VecDeque<T, A>) -> SelfTurn a
VecDeque<T>into aVec<T>.This never needs to re-allocate, but does need to do O(n) data movement if the circular buffer doesn't happen to be at the beginning of the allocation.
Examples
use VecDeque; // This one is *O*(1). let deque: = .collect; let ptr = deque.as_slices.0.as_ptr; let vec = Vecfrom; assert_eq!; assert_eq!; // This one needs data rearranging. let mut deque: = .collect; deque.push_front; deque.push_front; let ptr = deque.as_slices.1.as_ptr; let vec = Vecfrom; assert_eq!; assert_eq!;
impl<T, A: Allocator> IntoIterator for Vec<T, A>
fn into_iter(self: Self) -> <Self as >::IntoIterCreates a consuming iterator, that is, one that moves each value out of the vector (from start to end). The vector cannot be used after calling this.
Examples
let v = vec!; let mut v_iter = v.into_iter; let first_element: = v_iter.next; assert_eq!; assert_eq!; assert_eq!;
impl<T, I: SliceIndex<[T]>, A: Allocator> Index for Vec<T, A>
fn index(self: &Self, index: I) -> &<Self as >::Output
impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut for Vec<T, A>
fn index_mut(self: &mut Self, index: I) -> &mut <Self as >::Output
impl<T, N: usize> From for Vec<T>
fn from(s: [T; N]) -> Vec<T>Allocates a
Vec<T>and movess's items into it.Examples
assert_eq!;
impl<T, U> Into for Vec<T, A>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Vec<T, A>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Vec<T, A>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<T, U, A1: Allocator, A2: Allocator> PartialEq for super::Vec<T, A1>
fn eq(self: &Self, other: &Vec<U, A2>) -> boolfn ne(self: &Self, other: &Vec<U, A2>) -> bool
impl<T, U, A: Allocator> PartialEq for super::Vec<T, A>
fn eq(self: &Self, other: &&[U]) -> boolfn ne(self: &Self, other: &&[U]) -> bool
impl<T, U, A: Allocator> PartialEq for super::Vec<T, A>
fn eq(self: &Self, other: &[U]) -> boolfn ne(self: &Self, other: &[U]) -> bool
impl<T, U, A: Allocator> PartialEq for super::Vec<T, A>
fn eq(self: &Self, other: &&mut [U]) -> boolfn ne(self: &Self, other: &&mut [U]) -> bool
impl<T, U, A: Allocator, N: usize> PartialEq for super::Vec<T, A>
fn eq(self: &Self, other: &[U; N]) -> boolfn ne(self: &Self, other: &[U; N]) -> bool
impl<T, U, A: Allocator, N: usize> PartialEq for super::Vec<T, A>
fn eq(self: &Self, other: &&[U; N]) -> boolfn ne(self: &Self, other: &&[U; N]) -> bool
impl<T: Clone> From for Vec<T>
fn from(s: &[T]) -> Vec<T>Allocates a
Vec<T>and fills it by clonings's items.Examples
assert_eq!;
impl<T: Clone> From for Vec<T>
fn from(s: &mut [T]) -> Vec<T>Allocates a
Vec<T>and fills it by clonings's items.Examples
assert_eq!;
impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A>
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)Overwrites the contents of
selfwith a clone of the contents ofsource.This method is preferred over simply assigning
source.clone()toself, as it avoids reallocation if possible. Additionally, if the element typeToverridesclone_from(), this will reuse the resources ofself's elements as well.Examples
let x = vec!; let mut y = vec!; let yp: *const i32 = y.as_ptr; y.clone_from; // The value is the same assert_eq!; // And no reallocation occurred assert_eq!;
impl<T: Clone, N: usize> From for Vec<T>
fn from(s: &[T; N]) -> Vec<T>Allocates a
Vec<T>and fills it by clonings's items.Examples
assert_eq!;
impl<T: Clone, N: usize> From for Vec<T>
fn from(s: &mut [T; N]) -> Vec<T>Allocates a
Vec<T>and fills it by clonings's items.Examples
assert_eq!;
impl<T: Eq, A: Allocator> Eq for Vec<T, A>
impl<T: Hash, A: Allocator> Hash for Vec<T, A>
fn hash<H: Hasher>(self: &Self, state: &mut H)
impl<T: Ord, A: Allocator> Ord for Vec<T, A>
fn cmp(self: &Self, other: &Self) -> Ordering
impl<T: fmt::Debug, A: Allocator> Debug for Vec<T, A>
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result