Sized and unsized

For the compiler to translate written code into a binary format, it's necessary to know each type's size. As we discussed earlier, the size is important so that we can put other types on top when working on the stack, something that is easy if the size doesn't change with respect to the data it contains (a sized type). The best example for this is u32: it uses 32 bits (or 4 bytes), regardless of whether you store 0 or 10000900.

This isn't the case when the type is unsized or dynamically sized, the best example being a str. Depending on the number of characters, this type's size will vary considerably, and which is why instances are usually encountered in the form of slices.

Slices are Rust's way of providing generic algorithms to all kinds of data types, and they will be discussed more in Chapter 12, Algorithms of the Standard Library.

Slices work around the size issue by storing a fixed-size reference (&str) to the heap-allocated value, along with its length in bytes. Similar to pointers, this is a fixed-size view into a previously-unsized value. Every time a pointer of some kind (&, Rc, Box, Cell, and so on) is created, the reference is stored alongside the length and some (fixed size) metadata. The knowledge of sized versus unsized is especially useful when the type is previously unknown—when working with Rust's generics, for example.