rust armanriazi capacity reserve

The capacity method in Rust is used to check the current capacity of a Vec or String. It returns the number of elements that the collection can hold without allocating additional memory.

The reserve method is used to pre-allocate memory for a certain number of additional elements in a Vec or String. This can be useful when you know that you will be adding a specific number of elements to the collection, as it can help avoid frequent reallocations and improve performance. The reserve method takes a parameter specifying the number of additional elements to reserve.

Here's an example of how these methods can be used:

let mut vec = Vec::new();

println!("Current capacity: {}", vec.capacity()); // Output: 0

vec.reserve(10);
println!("Current capacity after reserving 10 elements: {}", vec.capacity()); // Output: 10

vec.push(1);
vec.push(2);
vec.push(3);

println!("Current capacity after adding 3 elements: {}", vec.capacity()); // Output: 10

vec.reserve(20);
println!("Current capacity after reserving additional 20 elements: {}", vec.capacity()); // Output: 30

In this example, we start with an empty Vec and use the reserve method to pre-allocate memory for 10 elements. After adding 3 elements, the capacity remains at 10. Then, we use reserve again to reserve an additional 20 elements, resulting in a capacity of 30.