5

According to the Rust documentation:

Vectors always allocate their data on the heap.

As I understand this, it means that:

  • Rust will allocate enough memory on the heap to store the type T in a contiguous fashion.
  • Rust will not individually box the items as they are placed into the vector.

In other words, if I add a few integers to a vector, while the Vec will allocate enough storage to store those integers, it's not also going to box those integers; introducing another layer of indirection.

I'm not sure how I can illustrate or confirm this with code examples but any help is appreciated.

trincot
  • 317,000
  • 35
  • 244
  • 286
Ralph Caraveo
  • 10,025
  • 7
  • 40
  • 52

1 Answers1

7

Yes, Vec<T> will store all items in a contiguous buffer rather than boxing them individually. The documentation states:

A contiguous growable array type, written Vec<T> but pronounced 'vector.'

Note that it is also possible to slice a vector, to get a &[T] (slice). Its documentation, again, confirms this:

A dynamically-sized view into a contiguous sequence, [T].

Slices are a view into a block of memory represented as a pointer and a length.

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305