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 = Vec::new();
vec.push(1);
vec.push(2);

assert_eq!(vec.len(), 2);
assert_eq!(vec[0], 1);

assert_eq!(vec.pop(), Some(2));
assert_eq!(vec.len(), 1);

vec[0] = 7;
assert_eq!(vec[0], 7);

vec.extend([1, 2, 3]);

for x in &vec {
    println!("{x}");
}
assert_eq!(vec, [7, 1, 2, 3]);

The [vec!] macro is provided for convenient initialization:

let mut vec1 = vec![1, 2, 3];
vec1.push(4);
let vec2 = Vec::from([1, 2, 3, 4]);
assert_eq!(vec1, vec2);

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![0; 5];
assert_eq!(vec, [0, 0, 0, 0, 0]);

// The following is equivalent, but potentially slower:
let mut vec = Vec::with_capacity(5);
vec.resize(5, 0);
assert_eq!(vec, [0, 0, 0, 0, 0]);

For more information, see Capacity and Reallocation.

Use a Vec<T> as an efficient stack:

let mut stack = Vec::new();

stack.push(1);
stack.push(2);
stack.push(3);

while let Some(top) = stack.pop() {
    // Prints 3, 2, 1
    println!("{top}");
}

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![0, 2, 4, 6];
println!("{}", v[1]); // 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:

fn read_slice(slice: &[usize]) {
    // ...
}

let v = vec![0, 1];
read_slice(&v);

// ... and that's all!
// you can also do it like this:
let u: &[usize] = &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 |
       +--------+--------+--------+--------+

Vec will never perform a "small optimization" where elements are actually stored on the stack for two reasons:

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() -> Self

Constructs a new, empty Vec<T>.

The vector will not allocate until elements are pushed onto it.

Examples

# #![allow(unused_mut)]
let mut vec: Vec<i32> = Vec::new();
const fn with_capacity(capacity: usize) -> Self

Constructs a new, empty Vec<T> with at least the specified capacity.

The vector will be able to hold at least capacity elements without reallocating. This method is allowed to allocate for more elements than capacity. If capacity is 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 the capacity method after construction.

For Vec<T> where T is a zero-sized type, there will be no allocation and the capacity will always be usize::MAX.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

let mut vec = Vec::with_capacity(10);

// The vector contains no items, even though it has capacity for more
assert_eq!(vec.len(), 0);
assert!(vec.capacity() >= 10);

// These are all done without reallocating...
for i in 0..10 {
    vec.push(i);
}
assert_eq!(vec.len(), 10);
assert!(vec.capacity() >= 10);

// ...but this may make the vector reallocate
vec.push(11);
assert_eq!(vec.len(), 11);
assert!(vec.capacity() >= 11);

// A vector of a zero-sized type will always over-allocate, since no
// allocation is necessary
let vec_units = Vec::<()>::with_capacity(10);
assert_eq!(vec_units.capacity(), usize::MAX);
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 capacity elements without reallocating. This method is allowed to allocate for more elements than capacity. If capacity is zero, the vector will not allocate.

Errors

Returns an error if the capacity exceeds isize::MAX bytes, or if the allocator reports allocation failure.

unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self

Creates 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 T is not a zero-sized type and the capacity is nonzero, ptr must have been allocated using the global allocator, such as via the alloc::alloc function. If T is a zero-sized type or the capacity is zero, ptr need only be non-null and aligned.
  • T needs to have the same alignment as what ptr was allocated with, if the pointer is required to be allocated. (T having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the dealloc requirement that memory must be allocated and deallocated with the same layout.)
  • The size of T times the capacity (ie. the allocated size in bytes), if nonzero, needs to be the same size as the pointer was allocated with. (Because similar to alignment, dealloc must be called with the same layout size.)
  • length needs to be less than or equal to capacity.
  • The first length values must be properly initialized values of type T.
  • capacity needs 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 of pointer::offset.

These requirements are always upheld by any ptr that has been allocated via Vec<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 C char array with length size_t, doing so is only safe if the array was initially allocated by a Vec or String. It's also not safe to build one from a Vec<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 (for u16), but after turning it into a Vec<u8> it'll be deallocated with alignment 1. To avoid these issues, it is often preferable to do casting/transmuting using slice::from_raw_parts instead.

The ownership of ptr is effectively transferred to the Vec<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 std::ptr;

let v = vec![1, 2, 3];

// Deconstruct the vector into parts.
let (p, len, cap) = v.into_raw_parts();

unsafe {
    // Overwrite memory with 4, 5, 6
    for i in 0..len {
        ptr::write(p.add(i), 4 + i);
    }

    // Put everything back together into a Vec
    let rebuilt = Vec::from_raw_parts(p, len, cap);
    assert_eq!(rebuilt, [4, 5, 6]);
}

Using memory that was allocated elsewhere:

use std::alloc::{alloc, Layout};

fn main() {
    let layout = Layout::array::<u32>(16).expect("overflow cannot happen");

    let vec = unsafe {
        let mem = alloc(layout).cast::<u32>();
        if mem.is_null() {
            return;
        }

        mem.write(1_000_000);

        Vec::from_raw_parts(mem, 1, 16)
    };

    assert_eq!(vec, &[1_000_000]);
    assert_eq!(vec.capacity(), 16);
}
unsafe fn from_parts(ptr: NonNull<T>, length: usize, capacity: usize) -> Self

Creates a Vec<T> directly from a NonNull pointer, a length, and a capacity.

Safety

This is highly unsafe, due to the number of invariants that aren't checked:

  • ptr must have been allocated using the global allocator, such as via the alloc::alloc function.
  • T needs to have the same alignment as what ptr was allocated with. (T having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the dealloc requirement that memory must be allocated and deallocated with the same layout.)
  • The size of T times the capacity (ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment, dealloc must be called with the same layout size.)
  • length needs to be less than or equal to capacity.
  • The first length values must be properly initialized values of type T.
  • capacity needs 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 of pointer::offset.

These requirements are always upheld by any ptr that has been allocated via Vec<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 C char array with length size_t, doing so is only safe if the array was initially allocated by a Vec or String. It's also not safe to build one from a Vec<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 (for u16), but after turning it into a Vec<u8> it'll be deallocated with alignment 1. To avoid these issues, it is often preferable to do casting/transmuting using NonNull::slice_from_raw_parts instead.

The ownership of ptr is effectively transferred to the Vec<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

#![feature(box_vec_non_null)]

let v = vec![1, 2, 3];

// Deconstruct the vector into parts.
let (p, len, cap) = v.into_parts();

unsafe {
    // Overwrite memory with 4, 5, 6
    for i in 0..len {
        p.add(i).write(4 + i);
    }

    // Put everything back together into a Vec
    let rebuilt = Vec::from_parts(p, len, cap);
    assert_eq!(rebuilt, [4, 5, 6]);
}

Using memory that was allocated elsewhere:

#![feature(box_vec_non_null)]

use std::alloc::{alloc, Layout};
use std::ptr::NonNull;

fn main() {
    let layout = Layout::array::<u32>(16).expect("overflow cannot happen");

    let vec = unsafe {
        let Some(mem) = NonNull::new(alloc(layout).cast::<u32>()) else {
            return;
        };

        mem.write(1_000_000);

        Vec::from_parts(mem, 1, 16)
    };

    assert_eq!(vec, &[1_000_000]);
    assert_eq!(vec.capacity(), 16);
}
fn from_fn<F>(length: usize, f: F) -> Self
where
    F: FnMut(usize) -> T

Creates a Vec<T> where each element is produced by calling f with that element's index while walking forward through the Vec<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 for Vec<T>s not iterators.

If length == 0, this produces an empty Vec<T> without ever calling f.

Example

#![feature(vec_from_fn)]

let vec = Vec::from_fn(5, |i| i);

// indexes are:  0  1  2  3  4
assert_eq!(vec, [0, 1, 2, 3, 4]);

let vec2 = Vec::from_fn(8, |i| i * 2);

// indexes are:   0  1  2  3  4  5   6   7
assert_eq!(vec2, [0, 2, 4, 6, 8, 10, 12, 14]);

let bool_vec = Vec::from_fn(5, |i| i % 2 == 0);

// indexes are:       0     1      2     3      4
assert_eq!(bool_vec, [true, false, true, false, true]);

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:

#![feature(vec_from_fn)]

let mut state = 1;
let a = Vec::from_fn(6, |_| { let x = state; state *= 2; x });

assert_eq!(a, [1, 2, 4, 8, 16, 32]);
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 a Vec with the from_raw_parts function; more generally, if T is non-zero-sized and the capacity is nonzero, one may use any method that calls dealloc with a layout of Layout::array::<T>(capacity); if T is zero-sized or the capacity is zero, nothing needs to be done.

Examples

let v: Vec<i32> = vec![-1, 0, 1];

let (ptr, len, cap) = v.into_raw_parts();

let rebuilt = unsafe {
    // We can now make changes to the components, such as
    // transmuting the raw pointer to a compatible type.
    let ptr = ptr as *mut u32;

    Vec::from_raw_parts(ptr, len, cap)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
fn into_parts(self: Self) -> (NonNull<T>, usize, usize)

Decomposes a Vec<T> into its raw components: (NonNull pointer, length, capacity).

Returns the NonNull 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_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 the NonNull pointer, length, and capacity back into a Vec with the from_parts function, allowing the destructor to perform the cleanup.

Examples

#![feature(box_vec_non_null)]

let v: Vec<i32> = vec![-1, 0, 1];

let (ptr, len, cap) = v.into_parts();

let rebuilt = unsafe {
    // We can now make changes to the components, such as
    // transmuting the raw pointer to a compatible type.
    let ptr = ptr.cast::<u32>();

    Vec::from_parts(ptr, len, cap)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
const fn const_make_global(self: Self) -> &'static [T]
where
    T: Freeze

Interns 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 Vec needs 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_with iterator and yields the removed items. replace_with does not need to be the same length as range.

range is removed even if the Splice iterator is not consumed before it is dropped.

It is unspecified how many elements are removed from the vector if the Splice value is leaked.

The input iterator replace_with is only consumed when the Splice value is dropped.

This is optimal if:

  • The tail (elements in the vector after range) is empty,
  • or replace_with yields fewer or equal elements than range'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![1, 2, 3, 4];
let new = [7, 8, 9];
let u: Vec<_> = v.splice(1..3, new).collect();
assert_eq!(v, [1, 7, 8, 9, 4]);
assert_eq!(u, [2, 3]);

Using splice to insert new items into a vector efficiently at a specific position indicated by an empty range:

let mut v = vec![1, 5];
let new = [2, 3, 4];
v.splice(1..1, new);
assert_eq!(v, [1, 2, 3, 4, 5]);
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 returns false, 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 ExtractIf is not exhausted, e.g. because it is dropped without iterating or the iteration short-circuits, then the remaining elements will be retained. Use extract_if().for_each(drop) if you do not need the returned iterator, or retain_mut with 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 = |x: &mut i32| { *x % 2 == 1 };
# let mut vec = vec![0, 1, 2, 3, 4, 5, 6];
# 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 {
    if some_predicate(&mut vec[i]) {
        let val = vec.remove(i);
        // your code here
#         extracted.push(val);
    } else {
        i += 1;
    }
}

# let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect();
# assert_eq!(vec, vec2);
# assert_eq!(extracted, extracted2);

But extract_if is easier to use. extract_if is 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 range is out of bounds.

Examples

Splitting a vector into even and odd values, reusing the original vector:

let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];

let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<Vec<_>>();
let odds = numbers;

assert_eq!(evens, vec![2, 4, 6, 8, 14]);
assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);

Using the range argument to only process a part of the vector:

let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2];
let ones = items.extract_if(7.., |x| *x == 1).collect::<Vec<_>>();
assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
assert_eq!(ones.len(), 3);

impl<T, A: Allocator> Vec<T, A>

const fn new_in(alloc: A) -> Self

Constructs a new, empty Vec<T, A>.

The vector will not allocate until elements are pushed onto it.

Examples

#![feature(allocator_api)]

use std::alloc::System;

# #[allow(unused_mut)]
let mut vec: Vec<i32, _> = Vec::new_in(System);
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 capacity elements without reallocating. This method is allowed to allocate for more elements than capacity. If capacity is zero, the vector will not allocate.

Errors

Returns an error if the capacity exceeds isize::MAX bytes, or if the allocator reports allocation failure.

unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self

Creates 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:

  • ptr must be currently allocated via the given allocator alloc.
  • T needs to have the same alignment as what ptr was allocated with. (T having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the dealloc requirement that memory must be allocated and deallocated with the same layout.)
  • The size of T times the capacity (ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment, dealloc must be called with the same layout size.)
  • length needs to be less than or equal to capacity.
  • The first length values must be properly initialized values of type T.
  • capacity needs 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 of pointer::offset.

These requirements are always upheld by any ptr that has been allocated via Vec<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 C char array with length size_t. It's also not safe to build one from a Vec<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 (for u16), but after turning it into a Vec<u8> it'll be deallocated with alignment 1.

The ownership of ptr is effectively transferred to the Vec<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

#![feature(allocator_api)]

use std::alloc::System;

use std::ptr;

let mut v = Vec::with_capacity_in(3, System);
v.push(1);
v.push(2);
v.push(3);

// Deconstruct the vector into parts.
let (p, len, cap, alloc) = v.into_raw_parts_with_alloc();

unsafe {
    // Overwrite memory with 4, 5, 6
    for i in 0..len {
        ptr::write(p.add(i), 4 + i);
    }

    // Put everything back together into a Vec
    let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
    assert_eq!(rebuilt, [4, 5, 6]);
}

Using memory that was allocated elsewhere:

#![feature(allocator_api)]

use std::alloc::{AllocError, Allocator, Global, Layout};

fn main() {
    let layout = Layout::array::<u32>(16).expect("overflow cannot happen");

    let vec = unsafe {
        let mem = match Global.allocate(layout) {
            Ok(mem) => mem.cast::<u32>().as_ptr(),
            Err(AllocError) => return,
        };

        mem.write(1_000_000);

        Vec::from_raw_parts_in(mem, 1, 16, Global)
    };

    assert_eq!(vec, &[1_000_000]);
    assert_eq!(vec.capacity(), 16);
}
unsafe fn from_parts_in(ptr: NonNull<T>, length: usize, capacity: usize, alloc: A) -> Self

Creates a Vec<T, A> directly from a NonNull pointer, a length, a capacity, and an allocator.

Safety

This is highly unsafe, due to the number of invariants that aren't checked:

  • ptr must be currently allocated via the given allocator alloc.
  • T needs to have the same alignment as what ptr was allocated with. (T having a less strict alignment is not sufficient, the alignment really needs to be equal to satisfy the dealloc requirement that memory must be allocated and deallocated with the same layout.)
  • The size of T times the capacity (ie. the allocated size in bytes) needs to be the same size as the pointer was allocated with. (Because similar to alignment, dealloc must be called with the same layout size.)
  • length needs to be less than or equal to capacity.
  • The first length values must be properly initialized values of type T.
  • capacity needs 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 of pointer::offset.

These requirements are always upheld by any ptr that has been allocated via Vec<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 C char array with length size_t. It's also not safe to build one from a Vec<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 (for u16), but after turning it into a Vec<u8> it'll be deallocated with alignment 1.

The ownership of ptr is effectively transferred to the Vec<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

#![feature(allocator_api, box_vec_non_null)]

use std::alloc::System;

let mut v = Vec::with_capacity_in(3, System);
v.push(1);
v.push(2);
v.push(3);

// Deconstruct the vector into parts.
let (p, len, cap, alloc) = v.into_parts_with_alloc();

unsafe {
    // Overwrite memory with 4, 5, 6
    for i in 0..len {
        p.add(i).write(4 + i);
    }

    // Put everything back together into a Vec
    let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone());
    assert_eq!(rebuilt, [4, 5, 6]);
}

Using memory that was allocated elsewhere:

#![feature(allocator_api, box_vec_non_null)]

use std::alloc::{AllocError, Allocator, Global, Layout};

fn main() {
    let layout = Layout::array::<u32>(16).expect("overflow cannot happen");

    let vec = unsafe {
        let mem = match Global.allocate(layout) {
            Ok(mem) => mem.cast::<u32>(),
            Err(AllocError) => return,
        };

        mem.write(1_000_000);

        Vec::from_parts_in(mem, 1, 16, Global)
    };

    assert_eq!(vec, &[1_000_000]);
    assert_eq!(vec.capacity(), 16);
}
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 a Vec with the from_raw_parts_in function, allowing the destructor to perform the cleanup.

Examples

#![feature(allocator_api)]

use std::alloc::System;

let mut v: Vec<i32, System> = Vec::new_in(System);
v.push(-1);
v.push(0);
v.push(1);

let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();

let rebuilt = unsafe {
    // We can now make changes to the components, such as
    // transmuting the raw pointer to a compatible type.
    let ptr = ptr as *mut u32;

    Vec::from_raw_parts_in(ptr, len, cap, alloc)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
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 NonNull 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_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 NonNull pointer, length, and capacity back into a Vec with the from_parts_in function, allowing the destructor to perform the cleanup.

Examples

#![feature(allocator_api, box_vec_non_null)]

use std::alloc::System;

let mut v: Vec<i32, System> = Vec::new_in(System);
v.push(-1);
v.push(0);
v.push(1);

let (ptr, len, cap, alloc) = v.into_parts_with_alloc();

let rebuilt = unsafe {
    // We can now make changes to the components, such as
    // transmuting the raw pointer to a compatible type.
    let ptr = ptr.cast::<u32>();

    Vec::from_parts_in(ptr, len, cap, alloc)
};
assert_eq!(rebuilt, [4294967295, 0, 1]);
const fn capacity(self: &Self) -> usize

Returns the total number of elements the vector can hold without reallocating.

Examples

let mut vec: Vec<i32> = Vec::with_capacity(10);
vec.push(42);
assert!(vec.capacity() >= 10);

A vector with zero-sized elements will always have a capacity of usize::MAX:

#[derive(Clone)]
struct ZeroSized;

fn main() {
    assert_eq!(std::mem::size_of::<ZeroSized>(), 0);
    let v = vec![ZeroSized; 0];
    assert_eq!(v.capacity(), usize::MAX);
}
fn reserve(self: &mut Self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the given Vec<T>. The collection may reserve more space to speculatively avoid frequent reallocations. After calling reserve, capacity will be greater than or equal to self.len() + additional. Does nothing if capacity is already sufficient.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

let mut vec = vec![1];
vec.reserve(10);
assert!(vec.capacity() >= 11);
fn reserve_exact(self: &mut Self, additional: usize)

Reserves the minimum capacity for at least additional more elements to be inserted in the given Vec<T>. Unlike reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling reserve_exact, capacity will be greater than or equal to self.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 reserve if future insertions are expected.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

let mut vec = vec![1];
vec.reserve_exact(10);
assert!(vec.capacity() >= 11);
fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional more elements to be inserted in the given Vec<T>. The collection may reserve more space to speculatively avoid frequent reallocations. After calling try_reserve, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). 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 std::collections::TryReserveError;

fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
    let mut output = Vec::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // very complicated
    }));

    Ok(output)
}
# process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve the minimum capacity for at least additional elements to be inserted in the given Vec<T>. Unlike try_reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling try_reserve_exact, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). 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_reserve if future insertions are expected.

Errors

If the capacity overflows, or the allocator reports a failure, then an error is returned.

Examples

use std::collections::TryReserveError;

fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
    let mut output = Vec::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve_exact(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.extend(data.iter().map(|&val| {
        val * 2 + 5 // very complicated
    }));

    Ok(output)
}
# process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
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. See Allocator::shrink for more details.

Examples

let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.shrink_to_fit();
assert!(vec.capacity() >= 3);
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 = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.shrink_to(4);
assert!(vec.capacity() >= 4);
vec.shrink_to(0);
assert!(vec.capacity() >= 3);
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![1, 2, 3];

let slice = v.into_boxed_slice();

Any excess capacity is removed:

let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);

assert!(vec.capacity() >= 10);
let slice = vec.into_boxed_slice();
assert_eq!(slice.into_vec().capacity(), 3);
fn truncate(self: &mut Self, len: usize)

Shortens the vector, keeping the first len elements and dropping the rest.

If len is greater or equal to the vector's current length, this has no effect.

The drain method can emulate truncate, 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![1, 2, 3, 4, 5];
vec.truncate(2);
assert_eq!(vec, [1, 2]);

No truncation occurs when len is greater than the vector's current length:

let mut vec = vec![1, 2, 3];
vec.truncate(8);
assert_eq!(vec, [1, 2, 3]);

Truncating when len == 0 is equivalent to calling the clear method.

let mut vec = vec![1, 2, 3];
vec.truncate(0);
assert_eq!(vec, []);
const fn as_slice(self: &Self) -> &[T]

Extracts a slice containing the entire vector.

Equivalent to &s[..].

Examples

use std::io::{self, Write};
let buffer = vec![1, 2, 3, 5, 8];
io::sink().write(buffer.as_slice()).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 std::io::{self, Read};
let mut buffer = vec![0; 3];
io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
const fn as_ptr(self: &Self) -> *const T

Returns 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, use as_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, and as_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![1, 2, 4];
let x_ptr = x.as_ptr();

unsafe {
    for i in 0..x.len() {
        assert_eq!(*x_ptr.add(i), 1 << i);
    }
}

Due to the aliasing guarantee, the following code is legal:

unsafe {
    let mut v = vec![0, 1, 2];
    let ptr1 = v.as_ptr();
    let _ = ptr1.read();
    let ptr2 = v.as_mut_ptr().offset(2);
    ptr2.write(2);
    // Notably, the write to `ptr2` did *not* invalidate `ptr1`
    // because it mutated a different element:
    let _ = ptr1.read();
}
const fn as_mut_ptr(self: &mut Self) -> *mut T

Returns 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, and as_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 T is not zero-sized and the capacity is nonzero, the pointer may be passed into dealloc with a layout of Layout::array::<T>(capacity) in order to deallocate the backing memory. If this is done, be careful not to run the destructor of the Vec, as dropping it will result in double-frees. Wrapping the Vec in a ManuallyDrop is the typical way to achieve this.

Examples

// Allocate vector big enough for 4 elements.
let size = 4;
let mut x: Vec<i32> = Vec::with_capacity(size);
let x_ptr = x.as_mut_ptr();

// Initialize elements via raw pointer writes, then set length.
unsafe {
    for i in 0..size {
        *x_ptr.add(i) = i as i32;
    }
    x.set_len(size);
}
assert_eq!(&*x, &[0, 1, 2, 3]);

Due to the aliasing guarantee, the following code is legal:

unsafe {
    let mut v = vec![0];
    let ptr1 = v.as_mut_ptr();
    ptr1.write(1);
    let ptr2 = v.as_mut_ptr();
    ptr2.write(2);
    // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
    ptr1.write(3);
}

Deallocating a vector using Box (which uses dealloc internally):

use std::mem::{ManuallyDrop, MaybeUninit};

let mut v = ManuallyDrop::new(vec![0, 1, 2]);
let ptr = v.as_mut_ptr();
let capacity = v.capacity();
let slice_ptr: *mut [MaybeUninit<i32>] =
    std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity);
drop(unsafe { Box::from_raw(slice_ptr) });
const fn as_non_null(self: &mut Self) -> NonNull<T>

Returns a NonNull pointer to the vector's buffer, or a dangling NonNull 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, and as_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

#![feature(box_vec_non_null)]

// Allocate vector big enough for 4 elements.
let size = 4;
let mut x: Vec<i32> = Vec::with_capacity(size);
let x_ptr = x.as_non_null();

// Initialize elements via raw pointer writes, then set length.
unsafe {
    for i in 0..size {
        x_ptr.add(i).write(i as i32);
    }
    x.set_len(size);
}
assert_eq!(&*x, &[0, 1, 2, 3]);

Due to the aliasing guarantee, the following code is legal:

#![feature(box_vec_non_null)]

unsafe {
    let mut v = vec![0];
    let ptr1 = v.as_non_null();
    ptr1.write(1);
    let ptr2 = v.as_non_null();
    ptr2.write(2);
    // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
    ptr1.write(3);
}
fn allocator(self: &Self) -> &A

Returns 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, or clear.

Safety

  • new_len must be less than or equal to capacity().
  • The elements at old_len..new_len must 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_len call:

let mut vec = vec![vec![1, 0, 0],
                   vec![0, 1, 0],
                   vec![0, 0, 1]];
// SAFETY:
// 1. `old_len..0` is empty so no elements need to be initialized.
// 2. `0 <= capacity` always holds whatever `capacity` is.
unsafe {
    vec.set_len(0);
#   // FIXME(https://github.com/rust-lang/miri/issues/3670):
#   // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
#   vec.set_len(3);
}

Normally, here, one would use clear instead to correctly drop the contents and thus not leak memory.

fn swap_remove(self: &mut Self, index: usize) -> T

Removes 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 remove instead.

Panics

Panics if index is out of bounds.

Examples

let mut v = vec!["foo", "bar", "baz", "qux"];

assert_eq!(v.swap_remove(1), "bar");
assert_eq!(v, ["foo", "qux", "baz"]);

assert_eq!(v.swap_remove(0), "foo");
assert_eq!(v, ["baz", "qux"]);
fn insert(self: &mut Self, index: usize, element: T)

Inserts an element at position index within the vector, shifting all elements after it to the right.

Panics

Panics if index > len.

Examples

let mut vec = vec!['a', 'b', 'c'];
vec.insert(1, 'd');
assert_eq!(vec, ['a', 'd', 'b', 'c']);
vec.insert(4, 'e');
assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']);

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 T

Inserts an element at position index within the vector, shifting all elements after it to the right, and returning a reference to the new element.

Panics

Panics if index > len.

Examples

#![feature(push_mut)]
let mut vec = vec![1, 3, 5, 9];
let x = vec.insert_mut(3, 6);
*x += 1;
assert_eq!(vec, [1, 3, 5, 7, 9]);

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) -> T

Removes and returns the element at position index within 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_remove instead. If you'd like to remove elements from the beginning of the Vec, consider using VecDeque::pop_front instead.

Panics

Panics if index is out of bounds.

Examples

let mut v = vec!['a', 'b', 'c'];
assert_eq!(v.remove(1), 'b');
assert_eq!(v, ['a', 'c']);
fn try_remove(self: &mut Self, index: usize) -> Option<T>

Remove and return the element at position index within the vector, shifting all elements after it to the left, or None if 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 using VecDeque::pop_front instead.

Examples

#![feature(vec_try_remove)]
let mut v = vec![1, 2, 3];
assert_eq!(v.try_remove(0), Some(1));
assert_eq!(v.try_remove(2), None);
fn retain<F>(self: &mut Self, f: F)
where
    F: FnMut(&T) -> bool

Retains only the elements specified by the predicate.

In other words, remove all elements e for which f(&e) returns false. 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![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);

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![1, 2, 3, 4, 5];
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
vec.retain(|_| *iter.next().unwrap());
assert_eq!(vec, [2, 3, 5]);
fn retain_mut<F>(self: &mut Self, f: F)
where
    F: FnMut(&mut T) -> bool

Retains only the elements specified by the predicate, passing a mutable reference to it.

In other words, remove all elements e such that f(&mut e) returns false. 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![1, 2, 3, 4];
vec.retain_mut(|x| if *x <= 3 {
    *x += 1;
    true
} else {
    false
});
assert_eq!(vec, [2, 3, 4]);
fn dedup_by_key<F, K>(self: &mut Self, key: F)
where
    F: FnMut(&mut T) -> K,
    K: PartialEq

Removes 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![10, 20, 21, 30, 20];

vec.dedup_by_key(|i| *i / 10);

assert_eq!(vec, [10, 20, 30, 20]);
fn dedup_by<F>(self: &mut Self, same_bucket: F)
where
    F: FnMut(&mut T, &mut T) -> bool

Removes all but the first of consecutive elements in the vector satisfying a given equality relation.

The same_bucket function 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 if same_bucket(a, b) returns true, a is removed.

If the vector is sorted, this removes all duplicates.

Examples

let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];

vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));

assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
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 push this method will not reallocate when there's insufficient capacity. The caller should use reserve or try_reserve to ensure that there is enough capacity.

Examples

A manual, panic-free alternative to [FromIterator]:

#![feature(vec_push_within_capacity)]

use std::collections::TryReserveError;
fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
    let mut vec = Vec::new();
    for value in iter {
        if let Err(value) = vec.push_within_capacity(value) {
            vec.try_reserve(1)?;
            // this cannot fail, the previous line either returned or added at least 1 free slot
            let _ = vec.push_within_capacity(value);
        }
    }
    Ok(vec)
}
assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));

Time complexity

Takes O(1) time.

fn pop(self: &mut Self) -> Option<T>

Removes the last element from a vector and returns it, or None if it is empty.

If you'd like to pop the first element, consider using VecDeque::pop_front instead.

Examples

let mut vec = vec![1, 2, 3];
assert_eq!(vec.pop(), Some(3));
assert_eq!(vec, [1, 2]);

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, or None if the predicate returns false or the vector is empty (the predicate will not be called in that case).

Examples

let mut vec = vec![1, 2, 3, 4];
let pred = |x: &mut i32| *x % 2 == 0;

assert_eq!(vec.pop_if(pred), Some(4));
assert_eq!(vec, [1, 2, 3]);
assert_eq!(vec.pop_if(pred), None);
fn peek_mut(self: &mut Self) -> Option<PeekMut<'_, T, A>>

Returns a mutable reference to the last item in the vector, or None if it is empty.

Examples

Basic usage:

#![feature(vec_peek_mut)]
let mut vec = Vec::new();
assert!(vec.peek_mut().is_none());

vec.push(1);
vec.push(5);
vec.push(2);
assert_eq!(vec.last(), Some(&2));
if let Some(mut val) = vec.peek_mut() {
    *val = 0;
}
assert_eq!(vec.last(), Some(&0));
fn append(self: &mut Self, other: &mut Self)

Moves all the elements of other into self, leaving other empty.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

let mut vec = vec![1, 2, 3];
let mut vec2 = vec![4, 5, 6];
vec.append(&mut vec2);
assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
assert_eq!(vec2, []);
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![1, 2, 3];
let u: Vec<_> = v.drain(1..).collect();
assert_eq!(v, &[1]);
assert_eq!(u, &[2, 3]);

// A full range clears the vector, like `clear()` does
v.drain(..);
assert_eq!(v, &[]);
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![1, 2, 3];

v.clear();

assert!(v.is_empty());
const fn len(self: &Self) -> usize

Returns the number of elements in the vector, also referred to as its 'length'.

Examples

let a = vec![1, 2, 3];
assert_eq!(a.len(), 3);
const fn is_empty(self: &Self) -> bool

Returns true if the vector contains no elements.

Examples

let mut v = Vec::new();
assert!(v.is_empty());

v.push(1);
assert!(!v.is_empty());
fn split_off(self: &mut Self, at: usize) -> Self
where
    A: Clone

Splits 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::take or mem::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!['a', 'b', 'c'];
let vec2 = vec.split_off(1);
assert_eq!(vec, ['a']);
assert_eq!(vec2, ['b', 'c']);
fn resize_with<F>(self: &mut Self, new_len: usize, f: F)
where
    F: FnMut() -> T

Resizes the Vec in-place so that len is equal to new_len.

If new_len is greater than len, the Vec is extended by the difference, with each additional slot filled with the result of calling the closure f. The return values from f will end up in the Vec in the order they have been generated.

If new_len is less than len, the Vec is simply truncated.

This method uses a closure to create new values on every push. If you'd rather Clone a given value, use Vec::resize. If you want to use the Default trait to generate values, you can pass Default::default as the second argument.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

let mut vec = vec![1, 2, 3];
vec.resize_with(5, Default::default);
assert_eq!(vec, [1, 2, 3, 0, 0]);

let mut vec = vec![];
let mut p = 1;
vec.resize_with(4, || { p *= 2; p });
assert_eq!(vec, [2, 4, 8, 16]);
fn leak<'a>(self: Self) -> &'a mut [T]
where
    A: 'a

Consumes and leaks the Vec, returning a mutable reference to the contents, &'a mut [T].

Note that the type T must 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![1, 2, 3];
let static_ref: &'static mut [usize] = x.leak();
static_ref[0] += 1;
assert_eq!(static_ref, &[2, 2, 3]);
# // FIXME(https://github.com/rust-lang/miri/issues/3670):
# // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
# drop(unsafe { Box::from_raw(static_ref) });
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_len method.

Examples

// Allocate vector big enough for 10 elements.
let mut v = Vec::with_capacity(10);

// Fill in the first 3 elements.
let uninit = v.spare_capacity_mut();
uninit[0].write(0);
uninit[1].write(1);
uninit[2].write(2);

// Mark the first 3 elements of the vector as being initialized.
unsafe {
    v.set_len(3);
}

assert_eq!(&v, &[0, 1, 2]);
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 of MaybeUninit<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_len method.

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 Vec you can use push, extend, extend_from_slice, extend_from_within, insert, append, resize or resize_with, depending on your exact needs.

Examples

#![feature(vec_split_at_spare)]

let mut v = vec![1, 1, 2];

// Reserve additional space big enough for 10 elements.
v.reserve(10);

let (init, uninit) = v.split_at_spare_mut();
let sum = init.iter().copied().sum::<u32>();

// Fill in the next 4 elements.
uninit[0].write(sum);
uninit[1].write(sum * 2);
uninit[2].write(sum * 3);
uninit[3].write(sum * 4);

// Mark the 4 elements of the vector as being initialized.
unsafe {
    let len = v.len();
    v.set_len(len + 4);
}

assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
fn into_chunks<N: usize>(self: Self) -> Vec<[T; N], A>

Groups every N elements in the Vec<T> into chunks to produce a Vec<[T; N]>, dropping elements in the remainder. N must 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

#![feature(vec_into_chunks)]

let vec = vec![0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(vec.into_chunks::<3>(), [[0, 1, 2], [3, 4, 5]]);

let vec = vec![0, 1, 2, 3];
let chunks: Vec<[u8; 10]> = vec.into_chunks();
assert!(chunks.is_empty());

let flat = vec![0; 8 * 8 * 8];
let reshaped: Vec<[[[u8; 8]; 8]; 8]> = flat.into_chunks().into_chunks().into_chunks();
assert_eq!(reshaped.len(), 1);
fn recycle<U>(self: Self) -> Vec<U, A>
where
    U: Recyclable<T>

This clears out this Vec and recycles the allocation into a new Vec. The item type of the resulting Vec needs to have the same size and alignment as the item type of the original Vec.

Examples

#![feature(vec_recycle, transmutability)]
let a: Vec<u8> = vec![0; 100];
let capacity = a.capacity();
let addr = a.as_ptr().addr();
let b: Vec<i8> = a.recycle();
assert_eq!(b.len(), 0);
assert_eq!(b.capacity(), capacity);
assert_eq!(b.as_ptr().addr(), addr);

The Recyclable bound prevents this method from being called when T and U have 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 when T or U are 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 a Vec<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![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
assert_eq!(vec.pop(), Some([7, 8, 9]));

let mut flattened = vec.into_flattened();
assert_eq!(flattened.pop(), Some(6));

impl<T, A: ~const Allocator> Vec<T, A>

const fn with_capacity_in(capacity: usize, alloc: A) -> Self

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 capacity elements without reallocating. This method is allowed to allocate for more elements than capacity. If capacity is 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 the capacity method after construction.

For Vec<T, A> where T is a zero-sized type, there will be no allocation and the capacity will always be usize::MAX.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

#![feature(allocator_api)]

use std::alloc::System;

let mut vec = Vec::with_capacity_in(10, System);

// The vector contains no items, even though it has capacity for more
assert_eq!(vec.len(), 0);
assert!(vec.capacity() >= 10);

// These are all done without reallocating...
for i in 0..10 {
    vec.push(i);
}
assert_eq!(vec.len(), 10);
assert!(vec.capacity() >= 10);

// ...but this may make the vector reallocate
vec.push(11);
assert_eq!(vec.len(), 11);
assert!(vec.capacity() >= 11);

// A vector of a zero-sized type will always over-allocate, since no
// allocation is necessary
let vec_units = Vec::<(), System>::with_capacity_in(10, System);
assert_eq!(vec_units.capacity(), usize::MAX);
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::MAX bytes.

Examples

let mut vec = vec![1, 2];
vec.push(3);
assert_eq!(vec, [1, 2, 3]);

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 T

Appends an element to the back of a collection, returning a reference to it.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

#![feature(push_mut)]


let mut vec = vec![1, 2];
let last = vec.push_mut(3);
assert_eq!(*last, 3);
assert_eq!(vec, [1, 2, 3]);

let last = vec.push_mut(3);
*last += 1;
assert_eq!(vec, [1, 2, 3, 4]);

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 Vec in-place so that len is equal to new_len.

If new_len is greater than len, the Vec is extended by the difference, with each additional slot filled with value. If new_len is less than len, the Vec is simply truncated.

This method requires T to implement Clone, in order to be able to clone the passed value. If you need more flexibility (or want to rely on Default instead of Clone), use Vec::resize_with. If you only need to resize to a smaller size, use Vec::truncate.

Panics

Panics if the new capacity exceeds isize::MAX bytes.

Examples

let mut vec = vec!["hello"];
vec.resize(3, "world");
assert_eq!(vec, ["hello", "world", "world"]);

let mut vec = vec!['a', 'b', 'c', 'd'];
vec.resize(2, '_');
assert_eq!(vec, ['a', 'b']);
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 this Vec. The other slice 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::MAX bytes.

Examples

let mut vec = vec![1];
vec.extend_from_slice(&[2, 3, 4]);
assert_eq!(vec, [1, 2, 3, 4]);
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.

src must be a range that can form a valid subslice of the Vec.

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::MAX bytes.

Examples

let mut characters = vec!['a', 'b', 'c', 'd', 'e'];
characters.extend_from_within(2..);
assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);

let mut numbers = vec![0, 1, 2, 3, 4];
numbers.extend_from_within(..2);
assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);

let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")];
strings.extend_from_within(1..=2);
assert_eq!(strings, ["hello", "world", "!", "world", "!"]);

impl<T: PartialEq, A: Allocator> Vec<T, A>

fn dedup(self: &mut Self)

Removes consecutive repeated elements in the vector according to the PartialEq trait implementation.

If the vector is sorted, this removes all duplicates.

Examples

let mut vec = vec![1, 2, 2, 3, 2];

vec.dedup();

assert_eq!(vec, [1, 2, 3, 2]);

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!(Vec::from("123"), vec![b'1', b'2', b'3']);

impl From for crate::vec::Vec<u8>

fn from(s: ByteString) -> Self

impl From for crate::vec::Vec<u8>

fn from(s: CString) -> Vec<u8>

Converts a CString into a [Vec]<[u8]>.

The conversion consumes the CString, and removes the terminating NUL byte.

impl From for crate::vec::Vec<u8>

fn from(string: String) -> Vec<u8>

Converts the given String to a vector Vec that holds values of type u8.

Examples

let s1 = String::from("hello world");
let v1 = Vec::from(s1);

for b in v1 {
    println!("{b}");
}

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 s already owns a Vec<T>, it will be returned directly. If s is borrowing a slice, a new Vec<T> will be allocated and filled by cloning s's items into it.

Examples

# use std::borrow::Cow;
let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
assert_eq!(Vec::from(o), Vec::from(b));

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) -> T

Returns 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) -> T
fn 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>) -> Self

Converts a boxed slice into a vector by transferring ownership of the existing heap allocation.

Examples

let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
assert_eq!(Vec::from(b), vec![1, 2, 3]);

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 a Vec<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>) -> Self

Turn a VecDeque<T> into a Vec<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 std::collections::VecDeque;

// This one is *O*(1).
let deque: VecDeque<_> = (1..5).collect();
let ptr = deque.as_slices().0.as_ptr();
let vec = Vec::from(deque);
assert_eq!(vec, [1, 2, 3, 4]);
assert_eq!(vec.as_ptr(), ptr);

// This one needs data rearranging.
let mut deque: VecDeque<_> = (1..5).collect();
deque.push_front(9);
deque.push_front(8);
let ptr = deque.as_slices().1.as_ptr();
let vec = Vec::from(deque);
assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
assert_eq!(vec.as_ptr(), ptr);

impl<T, A: Allocator> IntoIterator for Vec<T, A>

fn into_iter(self: Self) -> <Self as >::IntoIter

Creates 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!["a".to_string(), "b".to_string()];
let mut v_iter = v.into_iter();

let first_element: Option<String> = v_iter.next();

assert_eq!(first_element, Some("a".to_string()));
assert_eq!(v_iter.next(), Some("b".to_string()));
assert_eq!(v_iter.next(), None);

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 moves s's items into it.

Examples

assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);

impl<T, U> Into for Vec<T, A>

fn into(self: Self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses 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>) -> bool
fn 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]) -> bool
fn ne(self: &Self, other: &&[U]) -> bool

impl<T, U, A: Allocator> PartialEq for super::Vec<T, A>

fn eq(self: &Self, other: &[U]) -> bool
fn ne(self: &Self, other: &[U]) -> bool

impl<T, U, A: Allocator> PartialEq for super::Vec<T, A>

fn eq(self: &Self, other: &&mut [U]) -> bool
fn 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]) -> bool
fn 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]) -> bool
fn 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 cloning s's items.

Examples

assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);

impl<T: Clone> From for Vec<T>

fn from(s: &mut [T]) -> Vec<T>

Allocates a Vec<T> and fills it by cloning s's items.

Examples

assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);

impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A>

fn clone(self: &Self) -> Self
fn clone_from(self: &mut Self, source: &Self)

Overwrites the contents of self with a clone of the contents of source.

This method is preferred over simply assigning source.clone() to self, as it avoids reallocation if possible. Additionally, if the element type T overrides clone_from(), this will reuse the resources of self's elements as well.

Examples

let x = vec![5, 6, 7];
let mut y = vec![8, 9, 10];
let yp: *const i32 = y.as_ptr();

y.clone_from(&x);

// The value is the same
assert_eq!(x, y);

// And no reallocation occurred
assert_eq!(yp, y.as_ptr());

impl<T: Clone, N: usize> From for Vec<T>

fn from(s: &[T; N]) -> Vec<T>

Allocates a Vec<T> and fills it by cloning s's items.

Examples

assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);

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 cloning s's items.

Examples

assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);

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