Why does this read input before printing?

Why won’t the program print “Please enter your name” before waiting for input?

Well, it did. It’s just that, for performance reasons, standard output is buffered. The write completed, but it was only writing to memory. If you want it to actually display to the user, you have to trigger a flush. This can be done either by writing a newline, or by doing it explicitly:

io::Write::flush(&mut io::stdout()).expect("flush failed!");

// If you "use" `io::Write`...
io::stdout().flush().expect("flush failed!");

Also, is it possible to “do nothing” if a returned Result is Ok?

Sure. Just… do nothing.

match io::stdin().read_line(&mut name) {
    Ok(_) => { /* nothing */ },
    Err(err) => println!("Could not parse input: {}", err)
}    

The relevant requirement here is that all arms in a match have to have the same result type. In the case of println!, it results in a (); aside from an empty block (or another function that returns ()), you can just use a literal:

match io::stdin().read_line(&mut name) {
    Ok(_) => (),
    Err(err) => println!("Could not parse input: {}", err)
}

Leave a Comment