Does Rust box the individual items that are added

2019-06-24 15:41发布

问题:

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.

回答1:

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.



标签: vector rust heap