Can someone explain why this compiles:
fn main() {
let a = vec![1, 2, 3];
println!("{:?}", a[4]);
}
When running it, I got:
thread '' panicked at 'index out of bounds: the len is 3 but the index is 4', ../src/libcollections/vec.rs:1132
Maybe what you mean is :
This returns an
Option
so it will returnSome
orNone
. Compare this to:This accesses by reference so it directly accesses the
address
and causes the panic in your program.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 typeVec<i32>
4
is of an unknown integral typeVec<i32>
implements subscripting, soa[4]
type checksHaving a compiler reasoning about values is not unknown, and there are various ways to get it.
constexpr
for example)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).If you would like to access elements of the
Vec
with index checking, you can use theVec
as a slice and then use itsget
method. For example, consider the following code.This outputs: