I'm confused by what seem to be conflicting statements in the documentation for vectors in Rust:
A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard library type
Vec<T>
.
and
Vectors store their contents as contiguous arrays of
T
on the heap. This means that they must be able to know the size ofT
at compile time (that is, how many bytes are needed to store aT
?). The size of some things can't be known at compile time. For these you'll have to store a pointer to that thing: thankfully, theBox
type works perfectly for this.
Rust vectors are dynamically growable, but I don't see how that fits with the statement that their size must be known at compile time.
It's been a while since I've worked with a lower-level language where I have to think about memory allocation so I'm probably missing something obvious.
Note the wording:
they must be able to know the size of
T
This says that the size of an individual element must be known. The total count of elements, and thus the total amount of memory allocated, is not known.
When the vector allocates memory, it says "I want to store 12 FooBar
structs. One FooBar
is 24 bytes, therefore I need to allocate 288 bytes total".
The 12 is the dynamic capacity of the vector, the 24 is the static size of one element (the T
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With