String Capacity Growth With Push Str

Preallocate with with_capacity, append with push_str, and reserve headroom so string building runs in amortized constant time without repeated reallocation.

RustData Integrity

Code

snippet
fn join_labels(labels: &[&str]) -> String {
    // 预分配:push 过程中按需扩容,避免反复搬运
    let mut joined = String::with_capacity(48);
    for (index, label) in labels.iter().enumerate() {
        if index > 0 {
            joined.push_str(", ");
        }
        joined.push_str(label);
    }
    joined
}

fn main() {
    let mut buffer = String::with_capacity(32);
    println!("start: cap {}", buffer.capacity());

    buffer.push_str("stage-1");
    println!("pushed: len {} cap {}", buffer.len(), buffer.capacity());

    // reserve:保证再装 100 字节也不再扩容
    buffer.reserve(100);
    println!("reserved: cap {}", buffer.capacity());

    println!("joined: {}", join_labels(&["compile", "test", "package"]));
}

What the code does

The working surface is the functions join_labels and main — everything else is wiring.

Repetition is confined to for (index, label) in labels.iter().enumerate() — the rest of the file is straight-line.

Applying it

The primary signature is fn join_labels(labels: &[&str]) -> String

The demo output is labeled (start: cap, pushed: len, reserved: cap), so every printed line maps back to its originating operation.

main sequences join_labels; executing the file runs that flow once.

Statements that matter

for (index, label) in labels.iter().enumerate() {
if index > 0 {
joined.push_str(", ");
}
joined.push_str(label);
}

Interactive Tools for This Topic

FAQ

What does String Capacity Growth With Push Str print when run?
The script runs standalone; its 4 labeled outputs include `start: cap`, `pushed: len`, `reserved: cap`.