Will io::stdin().read_line ever fail?

Consider the following echo example

use std::io;

fn main() {
    let mut input = String::new();

    while io::stdin().read_line(&mut input).is_ok() {
        println!("{:?}", input);

    println!("How could I reach here?");

When I input an arbitrary string, the program echoes it back; when I send EOF with Ctrl+D, it prints an empty string; when I send SIGINT with Ctrl+C, it simply exits. As a user, (how) can I make io::stdin().read_line return an Err?

Probably the most common will be passing binary data (String expects valid UTF-8 stream), e.g. this will fail:

cargo run < /dev/urandom

See std::io::BufRead - Rust .

BTW you should also check Ok(usize) which is the number of bytes read. If it's 0/empty, the input has been closed and no more data will be read, see std::io::BufRead - Rust .


Another interesting example:

cargo run 0</tmp

I found it here. Curiously, the first suggestion from that page (0<&-) doesn't actually produce an error on my system.


I mean, there's no guarantee that the stdin pipe exists at all.