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

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.

主站蜘蛛池模板: 昌图县| 阿坝| 徐闻县| 日土县| 双峰县| 嘉善县| 南木林县| 广水市| 达尔| 博爱县| 嘉义市| 柘城县| 卓尼县| 芦溪县| 芦山县| 和顺县| 手游| 平阴县| 蓬安县| 呼图壁县| 庄河市| 沂源县| 阳谷县| 容城县| 开化县| 莱西市| 南丰县| 陆丰市| 新津县| 泸西县| 浑源县| 临颍县| 汝阳县| 东乡县| 西乌珠穆沁旗| 汉寿县| 株洲县| 洞口县| 英山县| 富锦市| 微博|