Skip to content

Commit

Permalink
Edit description of invalid array access
Browse files Browse the repository at this point in the history
Array invalid index result in compile time error rather than runtime
  • Loading branch information
Amjad50 committed Sep 10, 2020
1 parent cb28dee commit 77dced6
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
$ cargo run
$ cargo build
Compiling arrays v0.1.0 (file:///projects/arrays)
error: this operation will panic at runtime
--> src/main.rs:5:19
Expand Down
18 changes: 8 additions & 10 deletions src/ch03-02-data-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -315,32 +315,30 @@ get the value `2` from index `[1]` in the array.
##### Invalid Array Element Access

What happens if you try to access an element of an array that is past the end
of the array? Say you change the example to the following code, which will
compile but exit with an error when it runs:
of the array? If you change the example to the following code, it will not compile:

<span class="filename">Filename: src/main.rs</span>

```rust,ignore,does_not_compile
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs}}
```

Running this code using `cargo run` produces the following result:
Running this code using `cargo build` produces the following result:

```console
{{#include ../listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt}}
```

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.
When you attempt to compile code that has invalid array access, The rust compiler
will catch that and will not allow for a successful compilation.

This is the first example of Rust’s safety principles in action. In many
low-level languages, this kind of check is not done, and when you provide an
incorrect index, invalid memory can be accessed. Rust protects you against this
kind of error by immediately exiting instead of allowing the memory access and
continuing. Chapter 9 discusses more of Rust’s error handling.
kind of error by not allowing the program to compile, or it might panic at *runtime*
if the error could not identified at *compile time*, which would immediately exit the program
instead of allowing the invalid memory access to occur.
Chapter 9 discusses more of Rust’s error handling.

[comparing-the-guess-to-the-secret-number]:
ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number
Expand Down

0 comments on commit 77dced6

Please sign in to comment.