Why does the Rust compiler allow index out of bounds?

前端 未结 3 438
北海茫月
北海茫月 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:33

    If you would like to access elements of the Vec with index checking, you can use the Vec as a slice and then use its get method. For example, consider the following code.

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

    This outputs:

    Some(3)
    None
    

提交回复
热议问题