Does Rust box the individual items that are added to a vector?

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!