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

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.

主站蜘蛛池模板: 商丘市| 陇南市| 西乌| 察雅县| 涞源县| 安图县| 富阳市| 瓦房店市| 望奎县| 闵行区| 教育| 开远市| 理塘县| 桐乡市| 陵水| 石首市| 铅山县| 盖州市| 金昌市| 建宁县| 锦屏县| 玉环县| 康马县| 巩义市| 中西区| 上高县| 新河县| 内黄县| 民和| 蒙城县| 台前县| 松原市| 寿宁县| 竹溪县| 海阳市| 增城市| 六枝特区| 镇巴县| 新竹市| 宣武区| 赞皇县|