@@ -324,26 +324,39 @@ get the value `2` from index `[1]` in the array.
324
324
##### Invalid Array Element Access
325
325
326
326
What happens if you try to access an element of an array that is past the end
327
- of the array? Say you change the example to the following code , which will
328
- compile but exit with an error when it runs :
327
+ of the array? Say you change the example to the following, which uses code
328
+ similar to the guessing game in Chapter 2 to get an array index from the user :
329
329
330
330
<span class =" filename " >Filename: src/main.rs</span >
331
331
332
332
``` rust,ignore,does_not_compile
333
333
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs}}
334
334
```
335
335
336
- Running this code using ` cargo run ` produces the following result:
336
+ This code compiles successfully. If you run this code using ` cargo run ` and
337
+ enter 0, 1, 2, 3, or 4, the program will print out the corresponding value at
338
+ that index in the array. If you instead enter a number past the end of the
339
+ array, such as 10, you'll see output like this:
340
+
341
+ <!-- manual-regeneration
342
+ cd listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access
343
+ cargo run
344
+ 10
345
+ -->
337
346
338
347
``` console
339
- {{#include ../listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt}}
348
+ thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:19:19
349
+ note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
340
350
```
341
351
342
- The compilation didn’t produce any errors, but the program resulted in a
343
- * runtime* error and didn’t exit successfully. When you attempt to access an
352
+ The program resulted in a * runtime* error at the point of using an invalid
353
+ value in the indexing operation. The program exited at that point with an error
354
+ message and didn't execute the final ` println! ` . When you attempt to access an
344
355
element using indexing, Rust will check that the index you’ve specified is less
345
356
than the array length. If the index is greater than or equal to the array
346
- length, Rust will panic.
357
+ length, Rust will panic. This check has to happen at runtime, especially in
358
+ this case, because the compiler can't possibly know what the value a user
359
+ running the code will later enter.
347
360
348
361
This is the first example of Rust’s safety principles in action. In many
349
362
low-level languages, this kind of check is not done, and when you provide an
0 commit comments