Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a vector be both dynamic and known at compile time in Rust?

Tags:

rust

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 of T at compile time (that is, how many bytes are needed to store a T?). 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, the Box 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.

like image 423
KPD Avatar asked Dec 18 '22 08:12

KPD


1 Answers

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).

like image 63
Shepmaster Avatar answered Jun 15 '23 16:06

Shepmaster