With Capacity Preallocates Vec Storage

Preallocate Vec storage with with_capacity and reserve so pushes stay inside one allocation; printed len and capacity show exactly when growth fires.

RustData Integrity

Code

snippet
fn main() {
    // When the element count is known: with_capacity allocates once, so pushes stop re-growing
    let mut buffer = Vec::with_capacity(4);
    println!("empty but cap={}", buffer.capacity());

    for i in 0..4 {
        buffer.push(i * 10);
    }
    println!("len={} cap={}", buffer.len(), buffer.capacity());

    // Reallocation fires only past capacity: growth follows the Vec growth strategy
    buffer.push(40);
    println!("after growth len={} cap={}", buffer.len(), buffer.capacity());

    // reserve guarantees room for at least that many additional elements
    buffer.reserve(100);
    println!("after reserve cap={}", buffer.capacity());

    // shrink_to_fit hands back the excess capacity
    buffer.shrink_to_fit();
    println!("shrunk cap={}", buffer.capacity());
}

What the code does

Structurally, expect the function main and nothing else.

The file repeats itself only inside for i in 0..4.

Points of care

  • There is no dependency tree here — the platform is the whole dependency.

Applying it

Output lines are prefixed (empty but cap=, len=, after growth len=), making each step’s effect easy to spot.

Statements that matter

let mut buffer = Vec::with_capacity(4);
buffer.shrink_to_fit();
buffer.push(i * 10);

Interactive Tools for This Topic

FAQ

What does With Capacity Preallocates Vec Storage print when run?
The script runs standalone; its 5 labeled outputs include `empty but cap=`, `len=`, `after growth len=`.