Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 662
Ralph Caraveo Avatar asked Sep 24 '16 17:09

Ralph Caraveo


People also ask

How do vectors work in Rust?

Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O(1) indexing and push and pop operations in vector also take O(1) complexity.

What does box do in Rust?

All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box<T> . A box is a smart pointer to a heap allocated value of type T . When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed.

Is Box A pointer in Rust?

Because a Box<T> is a pointer, Rust always knows how much space a Box<T> needs: a pointer's size doesn't change based on the amount of data it's pointing to. This means we can put a Box<T> inside the Cons variant instead of another List value directly.

What does VEC mean in Rust?

A contiguous growable array type, written as Vec<T> , short for 'vector'.


1 Answers

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.

like image 136
Lukas Kalbertodt Avatar answered Oct 21 '22 04:10

Lukas Kalbertodt