(This question has also been posted to StackOverflow.)
When reading the input stream with read_line()
, if you don't follow the statement with a .expect()
the compiler will warn you that this `Result` may be an `Err` variant, which should be handled
.
What I want to understand is what kind of situation will trigger such error handling.
I've tried piping my program into another one ( ./my_program | echo "hello"
) so I wouldn't have the chance to enter any input and would supposedly be able to see the error handling in action. To my surprise it actually led to a panic state:
thread 'main' panicked at 'failed printing to stdout: Broken pipe (os error 32)', src/libstd/io/stdio.rs:792:9
In this code from the book The Rust Programming Language, we specify a string which I believe should be printed when the program isn't able to read the input stream:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
How can I actually see that behavior in action?