Vec<T>
8 methodsA 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
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
| Name | Type | Description |
|---|---|---|
| capacity | usize | Number of elements to pre-allocate space for. |
Returns
Vec<T>
Example
let mut v: Vec<i32> = Vec::with_capacity(10);
for i in 0..10 {
v.push(i);
}
// No reallocations happened during the loopvec.push(value: T)Appends an element to the back of a collection.
Parameters
| Name | Type | Description |
|---|---|---|
| value | T | Element to append. |
Returns
()
Example
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
let mut v = vec![1, 2, 3];
assert_eq!(v.pop(), Some(3));
assert_eq!(v, [1, 2]);vec.len() -> usizeReturns the number of elements in the vector, also referred to as its 'length'.
Returns
usize
Example
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
| Name | Type | Description |
|---|---|---|
| index | usize | Index of the element to retrieve. |
Returns
Option<&T>
Example
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
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
| Name | Type | Description |
|---|---|---|
| iter | impl IntoIterator<Item = T> | Iterator whose items are appended. |
Returns
()
Example
let mut v = vec![1, 2];
v.extend([3, 4, 5]);
assert_eq!(v, [1, 2, 3, 4, 5]);