I'm learning Rust and trying to understand the difference between compile-time errors and runtime panics when accessing array elements.
Consider the following code:
fn main() { let a: [u32; 5] = [1, 2, 3, 4, 5]; let b = [1, 2, 3]; println!("b is {:?}", b); println!("b at 0 is {}", b[4]); println!("Please enter an array index."); let mut index = String::new(); std::io::stdin() .read_line(&mut index) .expect("Failed to read line"); let index: usize = index .trim() .parse() .expect("index entered was not a number"); let element = a[index]; println!("The value of the element at index {index} is: {element}"); } I understand that both b[4] and a[index] access an index that may be out of bounds. The difference is that b[4] uses a literal index, while index is obtained from user input.
My understanding is that a[index] fails at runtime if the user enters an invalid index because the actual value is not known until the program executes.
However, I'm less certain about b[4]. Since the compiler knows the length of b is 3 and the index is 4, I would expect it to detect the problem during compilation. Is that what happens, or does the program compile successfully and panic at runtime when the expression is evaluated?
2 posts - 2 participants
