Skip to content

Flush stdout in Rust

Call flush() after print! when text must be visible before the next newline. Bring std::io::Write into scope first, because flush() is provided by that trait.

EXAMPLE: CI-CHECKEDCOMPILED · examples/format-output/src/output_pages.rs#output-flush-page
use std::io::{self, Write};

print!("Continue? [y/N] ");
io::stdout().flush().unwrap();

Rust’s standard output handle uses a shared buffer. When stdout is connected to a terminal, the standard library documents it as line-buffered: a newline normally flushes the buffered output automatically.

That is why println! usually appears immediately while a prompt written with print! can remain buffered. If the program then waits for input, the user may be staring at an invisible prompt.

For an interactive prompt, write the prompt and flush stdout before reading from stdin.

flush() comes from the std::io::Write trait. Importing std::io alone is not enough to make the trait method available.

EXAMPLE: CI-CHECKED FAILURECOMPILE-FAIL ASSERTED · examples/compile-fail/stdout-flush-trait-not-in-scope.rs#stdout-flush-trait-not-in-scope
fn main() {
    std::io::stdout().flush().unwrap();
}

The failure above is compiled intentionally in CI. The fix is to bring the trait into scope before calling the method:

use std::io::Write;
std::io::stdout().flush()?;

The checked example above imports both io and Write together. Application code can propagate the io::Result with ?; the example uses unwrap() only to keep the standalone snippet compact.

Do not add flush() after every output call. Complete terminal lines written with println! normally benefit from line buffering already. Manual flushing matters when output must cross the buffer boundary before a newline, especially prompts, progress fragments, and interactive terminal output.

For the newline choice itself, see print! vs println!. For many repeated writes, see the output macro overview and its checked stdout-locking example.