Create an empty vector with a given capacity.
Vec::with_capacity creates a new, empty Vec<T> with space pre-allocated for at least the specified number of elements. The vector can hold this many elements without reallocating.
This is useful when you know roughly how many elements you will push, since it avoids multiple heap reallocations as the vector grows. The actual capacity may be slightly larger than requested.
Note that with_capacity does not change the length of the vector — it remains empty until elements are added.
| Name | Description | Optional |
|---|---|---|
capacity |
The minimum number of elements the vector should be able to hold without reallocating. | No |
let mut v = Vec::with_capacity(10);
assert_eq!(v.len(), 0);
assert!(v.capacity() >= 10);
v.push(42);
assert_eq!(v.len(), 1);