forked from Jimskapt/rust-book-fr
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fixes rust-lang#2417. Get the index from user input instead of a const.
The compiler has gotten sufficiently smart regarding const evaluation to catch many trivial instances of array-index-out-of-bounds at compile time. However, the compiler can't read peoples' minds... yet.
- Loading branch information
1 parent
033f132
commit 1e99f44
Showing
3 changed files
with
39 additions
and
24 deletions.
There are no files selected for viewing
15 changes: 0 additions & 15 deletions
15
listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/output.txt
This file was deleted.
Oops, something went wrong.
21 changes: 19 additions & 2 deletions
21
listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access/src/main.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters