官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 桑日县| 小金县| 东方市| 太原市| 阜新市| 浦北县| 洪雅县| 剑河县| 南川市| 新昌县| 延津县| 资阳市| 常宁市| 怀远县| 禄劝| 茶陵县| 桐城市| 会理县| 漠河县| 连山| 临城县| 马边| 铁力市| 台湾省| 南投市| 济宁市| 石狮市| 富源县| 威海市| 潮安县| 隆子县| 霍州市| 三亚市| 临夏县| 许昌县| 彭泽县| 会昌县| 修文县| 金阳县| 腾冲县| 南部县|