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

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.

主站蜘蛛池模板: 桃源县| 新民市| 会昌县| 娱乐| 四子王旗| 丰城市| 昌江| 海晏县| 东兰县| 松滋市| 集贤县| 利辛县| 搜索| 陕西省| 清流县| 迁安市| 天门市| 宁明县| 屏东市| 阜新市| 金昌市| 綦江县| 宣武区| 光泽县| 秭归县| 三台县| 涞源县| 佳木斯市| 金乡县| 九寨沟县| 湘西| 和林格尔县| 皋兰县| 鸡西市| 深泽县| 廊坊市| 大宁县| 碌曲县| 清水县| 察哈| 攀枝花市|