Skip to content

Rust std::vec::Vec API

Rust's Vec<T> — a growable, heap-allocated contiguous sequence. The default collection for owned lists.

1 class · 8 methods

Vec<T>

8 methods

A contiguous growable array type, written Vec<T> but pronounced 'vector'.

Vec::new() -> Vec<T>

Constructs a new, empty Vec. The vector will not allocate until elements are pushed onto it.

Returns

Vec<T>

Example

rust
let v: Vec<i32> = Vec::new();
assert!(v.is_empty());
Vec::with_capacity(capacity: usize) -> Vec<T>

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

Parameters

NameTypeDescription
capacityusizeNumber of elements to pre-allocate space for.

Returns

Vec<T>

Example

rust
let mut v: Vec<i32> = Vec::with_capacity(10);
for i in 0..10 {
    v.push(i);
}
// No reallocations happened during the loop
vec.push(value: T)

Appends an element to the back of a collection.

Parameters

NameTypeDescription
valueTElement to append.

Returns

()

Example

rust
let mut v = vec![1, 2];
v.push(3);
assert_eq!(v, [1, 2, 3]);
vec.pop() -> Option<T>

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

Returns

Option<T>

Example

rust
let mut v = vec![1, 2, 3];
assert_eq!(v.pop(), Some(3));
assert_eq!(v, [1, 2]);
vec.len() -> usize

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

Returns

usize

Example

rust
let v = vec![1, 2, 3];
assert_eq!(v.len(), 3);
vec.get(index: usize) -> Option<&T>

Returns a reference to an element or subslice depending on the type of index, returning None if out of bounds.

Parameters

NameTypeDescription
indexusizeIndex of the element to retrieve.

Returns

Option<&T>

Example

rust
let v = vec![10, 20, 30];
assert_eq!(v.get(1), Some(&20));
assert_eq!(v.get(5), None);
vec.iter() -> Iter<T>

Returns an iterator that yields references to the elements of the vector in order.

Returns

Iter<T>

Example

rust
let v = vec![1, 2, 3];
let sum: i32 = v.iter().sum();
assert_eq!(sum, 6);
vec.extend<I: IntoIterator<Item = T>>(iter: I)

Extends a collection with the contents of an iterator.

Parameters

NameTypeDescription
iterimpl IntoIterator<Item = T>Iterator whose items are appended.

Returns

()

Example

rust
let mut v = vec![1, 2];
v.extend([3, 4, 5]);
assert_eq!(v, [1, 2, 3, 4, 5]);