Why Does an Out-of-Bounds Array Index Fail at Compile Time in One Case but at Runtime in Another?

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?

Why don't you try it yourself?

Thanks for the reply, I did try it out, and I inferred from the error that the issue would get caught at compile time. The reason I asked was because, I had posed the question on chat GPT and its response did not match what I was experiencing, and on a similar stack overflow question, the error did not occur at compile time, but at runtime, which if I took a wild guess would mean the behavior was not always the same, which would imply that some older Rust versions did not pick up the issue until runtime, when the program panicked.

It's better to ask the compiler. The compiler knows, the AI often does not.

To understand this, you have to know the 3 types of error
In computer science, theirs 3 type of error: Logic error, Runtime error, and Syntax error.
Logic error is when your logic went wrong and give out a wrong number. This is caused by using the wrong algorithm like:

fn main(){
    let a = 4;
    let b = 3;
    println!("the sum of {a}, {b} is {}", a - b);
}

You can see how instead of using a + b, I used a - b which causes a false output.

Runtime is when your code is running, it panics or just crashes. a lot of runtime error can be caught by the rust borrow checker like use after free. In your case, the runtime error is when you access a element bigger than the array, like b.len() is 3 but your accessing the 5th element, which doesn't exist.

Syntax error is when your compiler throw a error. Its when you break the language's rule, like:

function main(){
    println! "hello world" ;
}

This can also be called a Compile Time Error. (the rust Borrow checker's error is also a syntax error.)

Now looking at your code for the first element b[4], does the compiler know the index value? yes, so calling element 4 (which doesn't exist) is breaking the compiler's rule, it can catch this error at compile time because no matter what, it will crash in run time.

Now lets look at your second part:

 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];

does the compiler know the index value when compile? no, because what if you enter a 2? it will run successfully. only when you enter a value bigger than 4 it will crash. but your compiler don't know what the value is, it is only known when you run the program. So it will cause a runtime crash, which is a runtime error.
(I know I will have some English grammar ishu, cause I type this in like 2 mins. But I believe you won't read all of this.)

Catching errors that the compiler can prove would always happen when the program is run is something the compiler does on a "best effort" basis. That is, it catches things that are easy enough to catch, without guarantees as to what exact cases it can handle.

sorry for writing a big text for u to read :\.

In computer science, theirs 3 type of error: Logic error, Runtime error, and Syntax error.

Compiler errors are another error category, and they are technically not syntax errors.

There's also the error of the logic being correctly implemented, everything compiling correctly, the program does exactly what you told it to do, yet it doesn't do what you want.

A better classification is perhaps syntax errors, semantics errors, and pragmatics errors. In a compiled language, syntax errors are always compile-time errors. Semantic errors can be compile-time (eg. type errors in a typed language, or other violations of the language rules like using a variable before it’s declared) or runtime (eg. out-of-bounds indexing with a runtime value). Pragmatics errors are those that you mentioned: the program works exactly as written, but what was written was not what was intended.

Putting "the program doesn't compile", "the index is out of bounds", and "the program crashes due to a runtime type error" in the same category seems wrong.

It depends on the perspective, I’d say. For example, in this thread the error is fundamentally the same one in both cases: an out-of-bounds index was used. But in one case the compiler catches it, and in another case it doesn’t. And this is unintuitive to people not versed in compiler design and computability – indeed more consistent would be never trying to catch runtime errors at compile time. But that would be less useful and still not intuitive "because this is obviously an error, why doesn’t the compiler see it?"

The code is fine and b[4] would normally compile. What happens is that you get a "lint", from the compiler. A lint is when the compiler detects allowed but suspicious code.

error: this operation will panic at runtime
 --> src/main.rs:6:30
  |
6 |     println!("b at 0 is {}", b[4]);
  |                              ^^^^ index out of bounds: the length is 3 but the index is 4
  |
  = note: `#[deny(unconditional_panic)]` on by default

You can see at the bottom that you got the unconditional_panic lint, and it turned into a compilation error because the lint is set to deny by default.

You can turn it into a warning by saying at the top of your program:

#![warn(unconditional_panic)]

If you do that, the compilation will proceed with just a warning, and you'll get a panic at runtime:

warning: this operation will panic at runtime
 --> src/main.rs:8:30
  |
8 |     println!("b at 0 is {}", b[4]);
  |                              ^^^^ index out of bounds: the length is 3 but the index is 4
  |
note: the lint level is defined here
 --> src/main.rs:1:9
  |
1 | #![warn(unconditional_panic)]
  |         ^^^^^^^^^^^^^^^^^^^

You can also switch off the lint altogether:

#![allow(unconditional_panic)]

which will result in no warning at all.

Thank you, this clarified things alot.

The previous post was completely correct, but to give a bit of the why here:

Rust defines what the code does when you run it. It's very important that that not change so that people can upgrade toolchains without needing to rethink everything.

But just because it's well-defined what something does, that doesn't mean it's necessarily what you want. Thus we have lints that have far more flexibility to change. They can detect more cases over time, use heuristics that accept occasionally not linting on something bad to avoid too often linting on things that are fine, etc. These are usually just warnings, but in situations where even though its behaviour is defined we know it's very commonly not what someone wanted, they can default to errors, like this one.

Because you can turn them off -- and in fact we automatically disable them in your dependencies -- this lets us give you new helpful information about your code while still letting you continue to use other code.

tnks for the new info :D.

Frankly, one doesn't need to know much about compiler design to understand the core issue: compiler doesn't understand your program, but, more importantly, it's not possible to create compiler that would understand your program all the time. And this fundamental: not only compiler couldn't understand what happens in your program WRT to out-of-bounds access, but, in fact, nothing interesting about arbitrary program can ever be answered with guarantee.

Would your program leak memory? Compiler couldn't answer. Would your program access uninitialized variable? Compiler couldn't answer. Nothing “interesting” can be answered, decisively. You always get three answers, not two: “yes”, “no” and “maybe“.

Precisely. Since cimpiler can not answer questions decisively at compile time the only consistent approach would be to catch errors in Runtime. Like Javascript does or Pythong does…

But, well, people like to have problems detected at reported at compile-time! The whole point of Rust is to detect problems at compile-time!

And that's where the core dilemma starts: we want the compiler to do something that it couldn't ever do, decisively… means we should change the question.

Sometimes question is important enough to ask developer to do a lot of work to thelp the compiler: references, pointers, ownership and bazillion other things are imposed on the user where in machine code only integer (addresses of regions of memory) exist to help to separate “guarantee to be memory safe” programs from others. Because it's important. Compiler still give you an escape hatch (called unsafe), but normally you have to do a lot of “syntax dance” to help the compiler realize that all memory addresses that program uses are good and correct.

Can something like that be done for array indexes? Yes, absolutely, it's called dependent data types and there are languages that have them (WUFFS is even used in production). But it's hard to write code for these languages and thus with indexes Rust uses different approach: best-case effort. It tries to detect problems when it could, but when it couldn't… they are detected at runtime.