Why does rust need to know the size of types at compile time?

When reading the chapter Using Box to Point to Data on the Heap from the rust book, it says:

Boxes don’t have performance overhead, other than storing their data on the heap instead of on the stack. But they don’t have many extra capabilities either. You’ll use them most often in these situations:

  • When you have a type whose size can’t be known at compile time and you want to use a value of that type in a context that requires an exact size

Which kinds of context is necessary to know the size of the type? Why does it need to know it?

Any time you want to copy (or move) it, for example. This includes returning something by value.

1 Like

In order to be able to find things like parameters or struct items efficiently, rust needs them to have fixed sizes, so they are at fixed offsets in memory ( some things can be placed in CPU registers instead of memory, but registers have fixed sizes, usually 64 bits nowadays ). If the size isn't known, then a pointer needs to be used, which is what Box is. Vec also stores data of variable size, and has a pointer to the actual vector elements ( and also the length of the vector ).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.