Skip to content

String::shrink_to

String methods · Strings

Level: reference · for working programmers

One line: Shrinks the capacity toward a floor you name — never below len(), and never below min_capacity.

pub fn shrink_to(&mut self, min_capacity: usize)

Stable since 1.56.0.

The middle ground between keeping all the slack and giving it all back. s.shrink_to(32) says "trim this, but leave room for 32 bytes", which suits a buffer that is reused: you want the memory back after an unusually large item, without paying to regrow for every ordinary one.

The result is at least max(len(), min_capacity), and the allocator may leave it higher. A min_capacity below the current length is not an error — it is simply floored at len().

If the capacity is already at or below the floor, nothing happens.

Stable since 1.56.

Example

string_shrink_to.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let mut s = String::with_capacity(100);
    s.push_str("hello");
    println!("start        len {} capacity {}", s.len(), s.capacity());

    s.shrink_to(32);
    println!("shrink_to 32 len {} capacity {}", s.len(), s.capacity());

    // Never below len, whatever you ask for.
    s.shrink_to(0);
    println!("shrink_to 0  len {} capacity {}", s.len(), s.capacity());

    // Already small enough: nothing happens.
    let before = s.capacity();
    s.shrink_to(1000);
    println!("unchanged: {}", s.capacity() == before);

    // The reuse pattern: reclaim after a big item, keep a working floor.
    let mut buf = String::with_capacity(16);
    for item in ["short", &"x".repeat(200), "short"] {
        buf.clear();
        buf.push_str(item);
        buf.shrink_to(16);
        println!("len {:>3} capacity {:>3}", buf.len(), buf.capacity());
    }
}

Verified output of string_shrink_to.rs — regenerated by tools/run_examples.py, never hand-typed.

start        len 5 capacity 100
shrink_to 32 len 5 capacity 32
shrink_to 0  len 5 capacity 5
unchanged: true
len   5 capacity  16
len 200 capacity 200
len   5 capacity  16

See also

String::shrink_to in the standard library ↗

Po polsku

shrink_to to kompromis między trzymaniem całego zapasu a oddaniem go w całości: podajesz podłogę, poniżej której pojemność (capacity) nie zejdzie. Prośba nigdy nie niszczy zawartości — wynik to co najmniej max(len(), min_capacity), więc s.shrink_to(0) na pięciobajtowym łańcuchu znaków daje pojemność 5, a nie 0, i nie jest to błąd, tylko ucięcie żądania do długości. Sens tego widać dopiero przy buforze używanym w pętli: buf.shrink_to(16) oddaje pamięć po nietypowo dużym elemencie (w przykładzie 200 → 16), ale zostawia zapas, żeby krótkie wpisy nie zmuszały alokatora do ciągłego powiększania bufora — a gdy pojemność już jest poniżej podłogi, wywołanie po prostu nic nie robi.

Szukaj po polsku: pojemność łańcucha znaków · zmniejszanie pojemności bufora · rust String shrink_to · rust shrink_to vs shrink_to_fit