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.
use std::io::{self, Write};
print!("Continue? [y/N] ");
io::stdout().flush().unwrap();Why print! may not appear immediately
Section titled “Why print! may not appear immediately”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.
Fix “no method named flush”
Section titled “Fix “no method named flush””flush() comes from the std::io::Write trait. Importing std::io alone is not enough to make the trait method available.
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.
When you do not need an explicit flush
Section titled “When you do not need an explicit flush”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.