How vector capacity work in Rust

1 Answer

0 votes
fn main() {
    let mut v = Vec::new();
    println!("A: {}", v.capacity()); 
    
    v.push('a'); // capacity automatically increased 
    
    println!("B: {}", v.capacity()); 
    
    v.push('b'); 
    v.push('c'); 
    v.push('d'); 
    
    println!("C: {}", v.capacity()); 
    
    v.push('e'); // capacity automatically increased // reallocation
    
    println!("D: {}", v.capacity()); 
}



/*
run:

A: 0
B: 4
C: 4
D: 8

*/

 



answered Feb 7, 2023 by avibootz

Related questions

1 answer 153 views
1 answer 174 views
2 answers 248 views
1 answer 237 views
2 answers 258 views
1 answer 223 views
...