Reputation: 5694
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?
Upvotes: 2
Views: 940
Reputation: 30061
Let's follow the source:
std::io::Stdin::read_line
delegates to std::io::StdinLock::read_line
.std::io::StdinLock::read_line
delegates to a private append_to_string
function.append_to_string
returns an error on non-UTF-8 input.Let's try this:
$ rustc a.rs # your program
$ echo "\x99" | ./a
Guess the number!
Please input your guess.
thread 'main' panicked at 'Failed to read line: Custom { kind: InvalidData, error: StringError("stream did not contain valid UTF-8") }', src/libcore/result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
Upvotes: 7