kockburn
kockburn

Reputation: 17616

If a struct has a Vector field, does it get allocated on the heap?

Suppose I have a struct Train which contains a field called passenger_ids which itself represents a Vector of passenger identifiers.

struct Train {
  passenger_ids: Vector<u32>
}

Would Train be allocated on the heap since it holds a field of type Vector (which is allocated on the heap)? Or would it instead be allocated on the stack and the field point towards the heap?

Upvotes: 0

Views: 363

Answers (1)

Masklinn
Masklinn

Reputation: 42302

Would Train be allocated on the heap since it holds a field of type Vector (which is allocated on the heap)? Or would it instead be allocated on the stack and the field point towards the heap?

No, a train would not be allocated on the heap, and no a vector is not allocated on the heap.

A Vec is a normal structure which contains a pointer to a heap allocation. The Train, and the Vec it contains, will be allocated as a single unit wherever they are put (whether that's on the stack, or on the heap if Box-ed, or somewhere else).

The Vec will then, if and when items get added to it, create a heap allocation and put the items there.

Upvotes: 4

Related Questions