Which conditions would trigger error handling in "read_line" followed by "expect"?

(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?

At the end of the day, the stdin input stream is like any form of stream, such as a file (at least in Linux), so the question becomes:

when can reading from a file (descriptor) fail?

And at that point, there are many things that can go wrong: the file descriptor can refer to a directory, or to a file with no read permissions.

As a short repro, running your example program in linux with /tmp as its stdin:

cargo run < /tmp

triggers the .expect() path.

Thank you for your answer and example! A user on StackOverflow by the name of mcarton suggested inputting a non-UTF-8 character in the stream, which also triggers the behavior (e.g. echo "\x99" | ./my_program).

2 Likes

That's indeed a more realistic error case :sweat_smile:

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.