每条路原本都是错的,我们不过是修路的人…
Invalid Array Element Access中提到:
What happens if you try to access an element of an array that is past the end of the array? Say you change the example to the following code, which will compile but exit with an error when it runs:
加粗部分的内容大概意思是:下面的代码可以通过编译但是运行时将会由于发生错误而退出。
fn main() {
let a = [1, 2, 3, 4, 5];
let index = 10;
let element = a[index];// index out of bounds.
println!("The value of element is: {}", element);
}
对于了解过Rust语言的朋友来讲,对此肯定都是有些许疑问的。因为Rust在编译时期知道的信息已经足够多啦。类似这种数组越界的错误在编译期间是完全可以检测出来的。事实证明,我们通过rustc编译上面的代码是会报错的。
后来我在该书的Github的issues里面发现已经有人提出该问题啦。晚了将近20天没有成为吃螃蟹的人。
Chapter 3.2: Example “Invalid Array Element Access” is incorrect
瑕不掩瑜,The Rust Programming Language这本书总体而言,对于Rust的讲解真的很不错。不过建议控制流程的部分看RBE就够了.
分享自己的Rust学习过程,感兴趣的朋友可以参考一下:Rust学习经历