Finlay Weber
Finlay Weber

Reputation: 4163

Are Dynamically Sized Typed always on the heap?

My learning of Rust has got me to learn about Dynamically Sized Types (DST) and I understand these are types whose size cannot be known at compile time. E.g. str.

My question now is, will I be right to say that DST can never exist on the stack, and they only exit on the heap?

Also, will it be correct to say sized types on the other hand can exist on the stack:

(eg. let x:u32 = 10)

but can also be made to exist on the heap, for example via the use of Box

(eg let x: Box<u32> = Box::new(10))

Are these statements above correct?

Upvotes: 2

Views: 244

Answers (1)

Optimistic Peach
Optimistic Peach

Reputation: 4298

Unsized types are often best interpreted as "just the data". Wherever that data lives is not important to the definition of DSTs.

For example, you can have a dst living on the stack:

let x = [1, 2, 3];
let y = &x[..];

The array x lives on the stack and its data is understood as a dst when you put it under a reference while in y.

y has the type &[i32] -- that is, a reference to some i32s. In this case, the reference points to data on the stack.

Other notable places you can place DSTs are:

  • The heap through allocations (Box, Rc, Arc, Vec, etc.)
  • The read-only portion of your program (usually through string constants such as "abc").
  • Unknown places (through extern types in nightly code).

In essence, any type can exist on the stack and heap (barring lifetime related issues). If you have a sized type on the stack, box it up and you have it on the heap. If you want a slice on the stack, slice into an array or string. If you want a trait object, take a reference to a value on the stack, etc. etc.

Upvotes: 6

Related Questions