The cost of bounds checking in Rust is zero at runtime for safe code because the compiler optimizes away redundant checks, but it may incur a small, constant overhead for necessary checks to prevent panics on invalid access. Rust achieves this through its ownership system and strict compile-time guarantees, ensuring memory safety without the performance penalty typical of garbage-collected languages.
let v = vec![1, 2, 3];
let third = v.get(2); // Safe, returns Option<&i32>
let third = &v[2]; // Safe, panics if index is out of bounds
In debug builds, the compiler includes these checks to help catch bugs early, but in release builds (cargo build --release), aggressive optimizations often eliminate them entirely when the compiler can prove the index is valid.