Hello,
On the page 25 of the book The Rust Programming Language, 2nd Edition, there is an example. I coded this and ran cargo run.
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number=rand::thread_rng().gen_range(1..=100);
println!("Please input your guess.");
let mut guess=String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line.");
let guess:u32=guess
.trim()
.parse()
.expect("Please type a number!");
println!("You guessed: {guess}");
match guess.cmp(&secret_number){
Ordering::Less =>println!("Too small!"),
Ordering::Greater=>print!("Too big!"),
Ordering::Equal=>print!("You win!"),
}
}
After the cargo run, I input sdf, and then it outputed
thread 'main' panicked at src/main.rs:16:10:
Please type a number!: ParseIntError { kind: InvalidDigit }
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
error: process didn't exit successfully: target\debug\guessing_game.exe (exit code: 101)
It is weird, as I thought it should ouput
Please type a number!
May you tell me why didn't it output as I thought?
Result::expect (and Option::expect) will panic if the result is an error. So you'll have to handle the error and print your message instead of using expect.
If parse returns an Err Result variant because it couldn’t create a number from the string, the expect call will crash the game and print the message we give it.
Oh, I didn't realize that you want the program to crash. When it crashes, you will get a panic message and often a backtrace. When using expect you will also see the message you pass. You did get that message, it's on the 2nd line:
thread 'main' panicked at src/main.rs:16:10:
Please type a number!: ParseIntError { kind: InvalidDigit }
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace
error: process didn't exit successfully: target\debug\guessing_game.exe (exit code: 101)
Yes, don't call expect, which will panic as I mentioned. Instead, handle the error and print the output you'd like. This can be done with a match statement. I can give you the code, but you'd probably prefer to try it yourself so you can learn how to handle errors. This is covered in the book.
What do you mean "but"? The "crash the game" part refers to the panic. I don't see the contradiction.
(It also does print both your custom error message and the underlying error, you probably missed it or your IDE swallowed part of it. Don't use IDEs while learning.)