How declare a vector with specific capacity to prevent reallocation in Rust

1 Answer

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



/*
run:

A: 8
B: 8
C: 8
D: 8

*/

 



answered Feb 7, 2023 by avibootz

Related questions

1 answer 170 views
170 views asked Feb 7, 2023 by avibootz
2 answers 157 views
1 answer 172 views
1 answer 127 views
1 answer 117 views
...