Puzzle 17: Explanation
Explore how Rust vectors operate by managing length, capacity, and memory allocation. Understand vector growth strategies and performance impacts, including tips for efficient usage. This lesson helps you grasp the underlying mechanics of vectors for better Rust programming.
We'll cover the following...
Test it out
Hit “Run” to see the code’s output.
Explanation
Vectors contain two components: a length indicating how many elements (items) are stored within the vector and a buffer of contiguous heap memory that contains the data for each of the items, one after the other. This buffer itself is often larger than the total number of elements stored within the vector.
Vectors are a lot like arrays, but they have a variable size. We can create a vector with a capacity of zero using new. We can create a vector with a user-specified capacity using with_capacity. The capacity represents the total size of the vector.
When we add an item to a vector, the vector checks to see if ...