Can anyone offer a suggestion as to why the phenomena below is occurring? To me it seemed to be the sort of thing that the Rust compiler would catch.
use std::io;
fn main() {
let mut guess = String::new();
loop {
io::stdin().read_line(&mut guess).expect("Failed to read line");
let guess:u32 = guess.trim().parse().expect("Please type a number!");
println!("{}", guess);
}
}
The above compiles which I expected it NOT to compile. This is the issue I'm trying to resolve. Below is the output while running the app. It crashes after second entry.
10
10
20
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', guess.rs:8:46
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
result of running the above.
Here is the above code with the loop removed. Instead of the loop the same calls are being made - but two sets instead of a loop. This is to mirror what happened in the loop. This fails as I expected.
use std::io;
fn main() {
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read line");
// below represents what would have occurred in the loop.
let guess:u32 = guess.trim().parse().expect("Please type a number!");
println!("{}", guess);
let guess:u32 = guess.trim().parse().expect("Please type a number!");
println!("{}", guess);
}
below is the compiler error which I expected to occur at compile time for the code above.
error[E0599]: no method named `trim` found for type `u32` in the current scope
--> guess2.rs:12:31
|
12 | let guess:u32 = guess.trim().parse().expect("Please type a number!");
| ^^^^ method not found in `u32`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0599`.
The problem: when in a loop - it passes compilation - I expect that it should not pass compilation and should raise the same compilation error as if there were no loop.