Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 3.2 Invalid Array Element Access issue caught at runtime or compile time? #2629

Closed
Atyansh opened this issue Feb 22, 2021 · 1 comment

Comments

@Atyansh
Copy link

Atyansh commented Feb 22, 2021

Running this code using cargo run produces the following result:

$ cargo run
   Compiling arrays v0.1.0 (file:///projects/arrays)
error: this operation will panic at runtime
 --> src/main.rs:5:19
  |
5 |     let element = a[index];
  |                   ^^^^^^^^ index out of bounds: the length is 5 but the index is 10
  |
  = note: `#[deny(unconditional_panic)]` on by default

error: aborting due to previous error

error: could not compile `arrays`

To learn more, run the command again with --verbose.

The compilation didn’t produce any errors, but the program resulted in a runtime error and didn’t exit successfully. When you attempt to access an element using indexing, Rust will check that the index you’ve specified is less than the array length. If the index is greater than or equal to the array length, Rust will panic.

The text says that this issue is caught at runtime and not compile time. That seems confusing given that running cargo build will also catch this issue, which doesn't run the binary. The error message says that this operation will panic at runtime, which implies that this error was caught before runtime.

Secondary question: This error is caught when running cargo build, but NOT when running cargo check. I'm guessing this is because of some kind of constant folding optimization that cargo check doesn't perform. Wondering if it's something that we can catch with cargo check as well.

@Atyansh
Copy link
Author

Atyansh commented Feb 22, 2021

Never mind, I was going off of the book hosted on the website:
https://doc.rust-lang.org/book/ch03-02-data-types.html#invalid-array-element-access

I see this issue has been brought up in #2417

It was fixed in 79bafdc

However, I did not notice it before opening the issue. My bad.

@Atyansh Atyansh closed this as completed Feb 22, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant