Open
Description
思考?
// 可以正确编译: cargo build
let index = 10;
let element = a[index];
println!("The value of element is: {}", element);
// 编译报错:cargo build
println!("a[0] is: {}, a[6] is: {}", a[0], a[6]);// error: index out of bounds: the len is 5 but the index is 6
let element = a[10];
println!("The value of element is: {}", element);
为什么声明了一个变量值,然后通过这个变量值去取超过数组的索引时,不会报错。而直接使用常量值或明确的值时,会编译报错?
常量值的类型必须是 usize,否则报错:
| ^^^^^^^^ slice indices are of type
usizeor ranges of
usize``
这个应该是跟编译器有关。