Why does the Rust compiler allow index out of bounds?

前端 未结 3 480
北海茫月
北海茫月 2021-02-05 05:07

Can someone explain why this compiles:

fn main() {
    let a = vec![1, 2, 3];
    println!(\"{:?}\", a[4]);
}

When running it, I got:

3条回答
  •  不要未来只要你来
    2021-02-05 05:40

    Maybe what you mean is :

    fn main() {
        let a = vec![1, 2, 3];
        println!("{:?}", a[4]);
    }
    

    This returns an Option so it will return Some or None. Compare this to:

    fn main() {
        let a = vec![1, 2, 3];
        println!("{:?}", &a[4]);
    }
    

    This accesses by reference so it directly accesses the address and causes the panic in your program.

提交回复
热议问题