Skip to content

Commit

Permalink
Merge pull request #2566 from rust-lang/outsmarting-the-smartypants-c…
Browse files Browse the repository at this point in the history
…ompiler

Fixes #2417. Get the index from user input instead of a const.
  • Loading branch information
steveklabnik committed Jan 20, 2021
2 parents f0c83d3 + 79bafdc commit e724bd8
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 24 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,25 @@
use std::io;

fn main() {
let a = [1, 2, 3, 4, 5];
let index = 10;

println!("Please enter an array index.");

let mut index = String::new();

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 element is: {}", element);
println!(
"The value of the element at index {} is: {}",
index, element
);
}
27 changes: 20 additions & 7 deletions src/ch03-02-data-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,26 +324,39 @@ 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? Say you change the example to the following, which uses code
similar to the guessing game in Chapter 2 to get an array index from the user:

<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:
This code compiles successfully. If you run this code using `cargo run` and
enter 0, 1, 2, 3, or 4, the program will print out the corresponding value at
that index in the array. If you instead enter a number past the end of the
array, such as 10, you'll see output like this:

<!-- manual-regeneration
cd listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access
cargo run
10
-->

```console
{{#include ../listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt}}
thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:19:19
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```

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
The program resulted in a *runtime* error at the point of using an invalid
value in the indexing operation. The program exited at that point with an error
message and didn't execute the final `println!`. 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.
length, Rust will panic. This check has to happen at runtime, especially in
this case, because the compiler can't possibly know what the value a user
running the code will later enter.

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
Expand Down

0 comments on commit e724bd8

Please sign in to comment.