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
  • 263,463
  • 30
  • 215
  • 251
Ralph Caraveo
  • 9,727
  • 7
  • 38
  • 51

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
  • 66,297
  • 20
  • 206
  • 264