I’ll be honest: I initially wanted to describe all collections available in Rust as well as their related concepts. Then, I started to dig a bit

Rust's Vector

submited by
Style Pass
2021-08-08 16:30:15

I’ll be honest: I initially wanted to describe all collections available in Rust as well as their related concepts. Then, I started to dig a bit into it, and I decided it would have been (much) too long. For that reason, I’ll restrict the scope to the Vec type.

Just as with Java’s ArrayList, Vec is backed by an array. When the array reaches full capacity, Vec reserves a new array with more capacity and copies elements from the original array to the newly-created one. Then, it frees the former. Note that the collection may allocate a larger array than necessary to avoid frequent reallocations.

Functions that create new Vec initialize them with no items. If we want to create a Vec and values simultaneously, Rust offers the vec! macro. We can replace the above code with the following one-liner:

At that point, if you’ve already dabbled a bit in Rust, you probably learned nothing new. Instead of describing every function on Vec - they are pretty similar to those found in other languages - let’s explore around a bit.

Leave a Comment