Why is a slice a DST?

78 Views Asked by At

In rust, a slice is a portion of an array or vector.

When we create a slice, we know the number of elements it represents in array/vector, which means we know the size of the slice.

So why do we call slice a DST?

1

There are 1 best solutions below

4
bk2204 On

Whether a type is considered statically or dynamically sized type depends on whether we know its size at compile time. For example, we know that an i32 is 4 bytes in size, and we know this at compile time, so this is a statically sized type.

We do know the size of a slice when we produce it, but that happens at run time. The exact same code can produce different sizes of slice, so we have to consider it dynamically sized, since we can't know how much space to allocate for it when we're compiling.

Dynamically sized types are often allocated on the heap and are stored behind a pointer, which allows the compiler to allocate an appropriate amount of space at compile time (for the pointer). In such a case, the compiler allocates space for the pointer, and then the memory the pointer points to (the memory for the dynamically sized type) is allocated at runtime.