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

Arrays

An array is a fixed-size collection of elements of the same type. We declare them with square brackets:

let array = [1, 2, 3, 4];
let array: [i16; 4] = [1, 2, 3, 4];

The second line shows how to specify the type of an array. An alternative way to do that is to use a literal suffix:

let array = [1u8, 2, 3, 4];

A literal suffix is the composition of a literal (that is, a constant) and a type suffix, so with the 1 constant and the u8 type, we get 1u8. Literal suffixes can only be used on numbers. This declares an array of 4 elements of the u8 type. Array indexing starts at 0 and bounds checking is done at runtime. Bounds checking is used to prevent accessing memory that is out of bounds, for instance, trying to access the element after the end of an array. While this can slow down the software a bit, it can be optimized in many cases. The following code will trigger a panic because the 4 index is one past the end of the array:

println!("{}", array[4]);

At runtime, we see the following message:

thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 4', src/main.rs:5:20
note: Run with `RUST_BACKTRACE=1` for a backtrace.

Another way to declare an array is:

let array = [0u8; 100];

This declares an array of 100 elements, where all of them are 0.

主站蜘蛛池模板: 双城市| 新建县| 漾濞| 潞西市| 喜德县| 贵州省| 离岛区| 峡江县| 新疆| 延边| 康定县| 江源县| 达州市| 西平县| 九龙坡区| 靖西县| 泾川县| 东乡县| 襄城县| 萨迦县| 瓦房店市| 开封县| 清苑县| 金华市| 巴彦淖尔市| 灌阳县| 镇远县| 华蓥市| 皋兰县| 青海省| 盐城市| 福建省| 恭城| 古蔺县| 汉沽区| 迭部县| 屏东市| 东乌| 怀集县| 顺昌县| 辛集市|