std-method
Vec::shrink_to_fit
Ask the vector to reduce unused capacity as much as possible. The allocator may leave extra capacity; length and values do not change. Expected stdout (not executed): [5, 8] true Common mistake: Asserting that capacity always equals length after shrinking.
Formal Syntax & Structure
rust syntaxrust
pub fn shrink_to_fit(&mut self)Working Example
Example Snippetrust
fn main() { let mut v = Vec::with_capacity(10); v.extend([5, 8]); v.shrink_to_fit(); println!("{v:?} {}", v.capacity() >= v.len());}