std-method

Vec::with_capacity

Construct an empty vector with space for at least the requested number of elements. The argument counts elements, not bytes. Capacity is not length; zero-sized elements have special capacity behavior. Expected stdout (not executed): 0 true [7] Common mistake: Indexing reserved but uninitialized positions.

Formal Syntax & Structure

rust syntaxrust
pub fn with_capacity(capacity: usize) -> Vec<T>

Working Example

Example Snippetrust
fn main() {    let mut items = Vec::<u32>::with_capacity(4);    println!("{} {}", items.len(), items.capacity() >= 4);    items.push(7);    println!("{items:?}");}
Rust Reference