Sub topic 1
Printing with print! and println!
Prerequisites
This chapter assumes you can:
- Write and run a small Rust program with
cargo run, including amainfunction. - Declare variables with
let. - Read a function signature that returns
Result.
You don't need to know about traits yet. The later chapters on Display and Debug cover them.
What the macros do
println! and print! are macros, not functions. The ! marks a macro call. Both turn their arguments into text and write that text to standard output (stdout), the stream a terminal shows by default.
The only difference is the line ending:
print!writes exactly the text you give it.println!writes the text and then a newline character,\n.
fn main() {
println!("Hello, world!");
print!("one ");
print!("two ");
println!("three");
println!();
println!("done");
}This prints:
Hello, world!
one two three
doneCalling println!() with no arguments prints only a newline, which gives you a blank line. Calling print!() with no arguments prints nothing.
Why macros and not functions
Rust has no variadic functions, so a function can't take a format string and any number of arguments. A macro can. The compiler also parses the format string while it compiles your program, so a mismatch between placeholders and arguments is a compile error, not a run-time surprise. The last chapter in this tutorial covers those checks.
One consequence matters right away. The first argument must be a string literal written in the source. A variable holding a string won't work.
fn main() {
let message = "hello";
// println!(message); // compile error: format argument must be a string literal
println!("{}", message); // correct
println!("{message}"); // also correct
}Without this rule, text from a user or a file could contain {} and be treated as a format string. If you want to print a string you already have, pass it as an argument to "{}".
Newlines and long literals
println! always appends \n, on every operating system. It does not write \r\n on Windows. Terminals handle this correctly, but keep it in mind if you write output to a file that another tool reads.
Inside a string literal you can use escapes such as \n, \t, \" and \\. A literal can also span several source lines:
fn main() {
println!("first line
second line");
println!("a \
b");
}The first call prints two lines, and the line break in the source becomes part of the output. In the second call, a backslash at the end of a source line removes that line break and the leading spaces on the next line. It prints a b.
Where the text goes
The text from a print macro doesn't go straight to the terminal. It passes through a buffer that Rust keeps for stdout.
Before the diagram, note that the chapter diagram follows below in the required form.
Rust's stdout is line-buffered. It holds text until it sees a newline, then writes everything up to that newline. This behavior is the same whether stdout is a terminal or a pipe. Each print call also locks stdout for its duration, so two threads calling println! won't mix characters within a single call. Lines from different threads can still interleave with each other.
Prompts and flushing
Because of the line buffer, print! text without a newline may not appear right away. This matters for prompts:
use std::io::{self, Write};
fn main() -> io::Result<()> {
print!("Your name: ");
io::stdout().flush()?;
let mut name = String::new();
io::stdin().read_line(&mut name)?;
println!("Hello, {}!", name.trim());
Ok(())
}Without the flush() call, the prompt can stay in the buffer while the program waits for input. flush forces the buffered text out. The Write trait must be in scope for flush to be available, which is why the use line imports it.
The final println! doesn't need a flush. Its newline triggers the write, and Rust also flushes stdout when the program exits normally.
Failure: print can panic
Writing to stdout can fail. The usual cause is a closed pipe. Suppose you run a program that prints many lines and pipe it into head -1. After head exits, the next write fails.
The print macros don't return a Result. If the write fails, they panic with a message like this:
thread 'main' panicked at library/std/src/io/stdio.rs:
failed printing to stdout: Broken pipe (os error 32)For quick programs and learning, this is acceptable. For command-line tools that are meant to be piped, write to stdout yourself and handle the error. The next section shows how.
Printing many lines efficiently
Each println! locks stdout and, because of the line buffer, can make a system call per line. For a few lines this cost doesn't matter. For hundreds of thousands of lines it does.
You can lock stdout once, wrap it in a BufWriter, and use writeln!, which is the same as println! but writes to any destination you choose:
use std::io::{self, BufWriter, Write};
fn main() -> io::Result<()> {
let stdout = io::stdout();
let mut out = BufWriter::new(stdout.lock());
for i in 1..=5 {
writeln!(out, "line {i}")?;
}
out.flush()?;
Ok(())
}Here writeln! returns a Result, so you handle a broken pipe with ? instead of a panic. The BufWriter collects many lines and writes them in large chunks. Call flush() at the end so you see any write error. If you rely on the BufWriter being dropped, it flushes but ignores errors.
Choosing between the four macros
| Macro | Stream | Adds newline |
|---|---|---|
| `print!` | stdout | No |
| `println!` | stdout | Yes |
| `eprint!` | stderr | No |
| `eprintln!` | stderr | Yes |
Use stdout for a program's results and stderr for diagnostics and errors. Then program > result.txt saves only the results while warnings still appear on screen. Later chapters cover eprintln! in more detail.
Common mistakes
- Forgetting to flush after
print!. The prompt appears late or not at all. Callio::stdout().flush(). - Passing a variable as the format string. Use
println!("{}", text), notprintln!(text). - Using
println!for large output in a pipeline. Lock stdout and usewriteln!so you can handle errors. - Mixing results and diagnostics on stdout. Send diagnostics to stderr.
Exercise
Your program runs print!("Enter a number: "); and then reads a line from standard input. The prompt doesn't appear until after you type. What is the cause, and what is the fix?
Show answer
Stdout is line-buffered, and the prompt has no newline, so it stays in the buffer while the program waits for input. Add use std::io::Write; and call io::stdout().flush()? (or .unwrap() in a program without Result) right after the print!.
Exercise
Why does let fmt = "x = {}"; println!(fmt, 5); fail to compile, and how do you write it correctly?
Show answer
The first argument of println! must be a string literal written in the source, so the compiler can check the placeholders. Write println!("x = {}", 5);. To print a string you already hold, pass it as an argument: println!("{}", fmt);.