Why does the Rust compiler allow index out of bounds?

前端 未结 3 436
北海茫月
北海茫月 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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 05:49

    In order to understand the issue, you have to think about it in terms of what the compiler sees.

    Typically, a compiler never reasons about the value of an expression, only about its type. Thus:

    • a is of type Vec<i32>
    • 4 is of an unknown integral type
    • Vec<i32> implements subscripting, so a[4] type checks

    Having a compiler reasoning about values is not unknown, and there are various ways to get it.

    • you can allow evaluation of some expression at compile-time (C++ constexpr for example)
    • you can encode value into types (C++ non-type template parameters, using Peano's numbers)
    • you can use dependent typing which bridges the gap between types and values

    Rust does not support any of these at this point in time, and while there has been interest for the former two it will certainly not be done before 1.0.

    Thus, the values are checked at runtime, and the implementation of Vec correctly bails out (here failing).

    0 讨论(0)
提交回复
热议问题