Rust print without newline: print! vs println!
Use print! when Rust should write to stdout without adding a newline. Use println! when the output should end with a newline. If a no-newline prompt must appear immediately, call stdout().flush() after print!.
print!("building...");
println!(" done");print! vs println!
Section titled “print! vs println!”| Macro | Destination | Adds a newline |
|---|---|---|
print! |
stdout | no |
println! |
stdout | yes |
Both macros use Rust’s normal formatting syntax. The difference here is the line ending, not how values are formatted.
Print without a newline
Section titled “Print without a newline”print! leaves the cursor immediately after the formatted text. It is useful for prompts, progress fragments, and output that intentionally continues on the same line.
The important catch is buffering. When stdout is connected to a terminal it is commonly line-buffered, so output without a newline may remain in the buffer.
Print without a newline and show it immediately
Section titled “Print without a newline and show it immediately”For an interactive prompt, import std::io::Write, call print!, and then flush stdout:
use std::io::{self, Write};
print!("Continue? [y/N] ");
io::stdout().flush().unwrap();The Write trait import is required for the flush() method. The dedicated flush stdout guide covers that trait requirement and the common compiler error when it is missing.
Use println! for complete lines
Section titled “Use println! for complete lines”For ordinary terminal output, println! is the default. It appends a newline and works naturally with line-buffered stdout.
Rust documents the newline emitted by println! as a line feed (\n) on every platform.
Repeated writes
Section titled “Repeated writes”Both macros lock stdout on each call. For occasional output that is exactly what you want. In a hot loop, repeatedly acquiring the lock can become avoidable overhead.
Lock stdout once and use write! or writeln! through the locked handle when you have many writes. The output macros overview contains a CI-checked example of that pattern.
Primary output only
Section titled “Primary output only”The standard library documentation positions these macros for primary program output. If text is an error, warning, or progress message that should stay separate from piped data, use stderr through eprint! or eprintln!.
If the main question is which output macro fits a destination and newline requirement, use the Output Macro Chooser.