Sub topic 6
Showing a prompt and flushing stdout
This chapter assumes you can already read a line with read_line, handle its io::Result with ?, and run programs with cargo run. Here you will make a prompt such as Enter your age: appear before the program waits for input.
Why a prompt can go missing
println! writes text and a newline. A prompt usually stays on the same line as the cursor, so you want print!, which writes no newline.
That is where the trouble starts. Rust's standard output is line buffered. Text goes into an in-memory buffer first, and the buffer is sent to the terminal only when it sees a newline or is flushed. A prompt without a newline can sit in the buffer while the program blocks on read_line. The user sees a blank screen and does not know what to type.
Flushing explicitly
flush forces the buffer out. It is a method of the Write trait, so you must import that trait. It also returns an io::Result<()>, which you handle the same way as the result of read_line.
use std::io::{self, Write};
fn main() -> io::Result<()> {
print!("Enter your age: ");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
match input.trim().parse::<u32>() {
Ok(age) => println!("Next year you will be {}.", age + 1),
Err(e) => println!("Not a valid number: {e}"),
}
Ok(())
}Here is what each line does:
use std::io::{self, Write}brings in both theiomodule and theWritetrait.print!queues the prompt in the buffer.io::stdout().flush()?sends the queued text to the terminal. The?returns early frommainif the flush fails.read_linenow blocks, and the user can see what to type.
A reusable prompt function
Once you have more than one prompt, repeating the print and flush pair gets tedious. Put it in a function:
use std::io::{self, Write};
fn prompt(message: &str) -> io::Result<String> {
print!("{message}");
io::stdout().flush()?;
let mut line = String::new();
io::stdin().read_line(&mut line)?;
Ok(line.trim().to_string())
}
fn main() -> io::Result<()> {
let name = prompt("Your name: ")?;
let city = prompt("Your city: ")?;
println!("Hello, {name} from {city}!");
Ok(())
}The function returns the trimmed text, so callers never see the newline.
Common errors
- Forgetting
use std::io::Write. The compiler reports that no method namedflushis found forStdout, and it suggests importing the trait. The method exists, but Rust only lets you call trait methods when the trait is in scope. - Forgetting to flush. The program compiles and runs, but the prompt appears late or only after the user has typed. The symptom depends on the terminal, which is why this bug is easy to miss.
- Ignoring the result. Writing
io::stdout().flush();without?orexpectproduces anunused_must_usewarning. A flush can fail, for example when stdout is a closed pipe, so handle it. - Using
println!for the prompt. It works, but the user types on the line below the prompt. That is a style choice, not a bug.
Exercises
Exercise
A program calls print!("Name: ") and then read_line, but the prompt does not appear until after the user presses Enter. Why does this happen, and what one line fixes it?
Show answer
Standard output is line buffered. The prompt has no newline, so it stays in the buffer while read_line blocks. Add io::stdout().flush()?; after the print!, with use std::io::Write; in scope.
Exercise
You add io::stdout().flush()?; and the compiler says no method named flush was found for struct Stdout. What is missing?
Show answer
The Write trait is not in scope. Add use std::io::Write;, or write use std::io::{self, Write};.