Learning rust and tried running this code (https://godbolt.org/z/b6Yrj3dfx):
fn main() {
let foo = vec![1,2,3];
println!("Value: {}", unsafe { foo.get_unchecked(3) });
}
Output:
thread 'main' panicked at core/src/panicking.rs:221:5:
unsafe precondition(s) violated: slice::get_unchecked requires that the index is within the slice
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread caused non-unwinding panic. aborting.
Program terminated with signal: SIGSEGV
I was expecting the program to print out some random value just like in C/C++, but from the error message it seems that it’s still doing bounds checking?
Documentation of get_unchecked:
Returns a reference to an element or subslice, without doing bounds checking.
What gives?
>Solution :
By using unsafe, you promised to not call get_unchecked() with an out of bounds index. You broke this promise. You invoked Undefined Behavior. Now Rust is free to do whatever it wants – and that includes panicking (in fact, a deterministic panic is probably the best outcome you can expect in this scenario). This is why Rust is allowed to do what it does.
As for why it does what it do, the reason is to have a safety net. In debug builds, Rust will make extra assertions to help you detect UB in your code. In release mode, this will be disabled, so the code can be the most performant possible.