Sub topic 13
format!, eprintln!, write!, and friends
This chapter assumes you know println! with {} and {:?}, basic traits, and the Result type with the ? operator. It covers the other macros built on the same format-string machinery. They differ in where the text goes: a new String, standard error, or any writer you choose.
One engine, several destinations
Every macro in this family takes a format string and arguments, and checks them at compile time. The only difference is the destination.
| Macro | Destination | Returns |
|---|---|---|
| `print!`, `println!` | standard output | `()` |
| `eprint!`, `eprintln!` | standard error | `()` |
| `format!` | a new `String` | `String` |
| `write!`, `writeln!` | any value with a `write_fmt` method | `Result` |
The ln variants append a newline. writeln!(w) with no format string writes only a newline.
format!: build a String
format! works exactly like println!, but it returns the text as an owned String and prints nothing. Use it when you need the text again, for example to store it, pass it on, or measure it.
fn main() {
let name = "Ferris";
let s = format!("{name:>8}|");
println!("{s}");
let line = format!("{}-{}", 1, 2);
println!("{line} has {} bytes", line.len());
}This prints Ferris| and then 1-2 has 3 bytes. The width applies to the argument as it did in println!.
Each call allocates a new String. In a loop that builds one large result, appending with write! (below) avoids creating many short-lived strings.
print! and stdout buffering
Standard output is usually line-buffered when it is attached to a terminal. Text from print! without a newline may not appear until the buffer is flushed. Call flush when a prompt must appear before the program waits for input.
use std::io::{self, Write};
fn main() {
print!("Enter name: ");
io::stdout().flush().unwrap();
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
println!("Hello, {}!", line.trim());
}Without flush, the prompt may show up after you type your answer.
eprintln!: errors and diagnostics
eprintln! writes to standard error, a separate stream. When a user redirects output with program > out.txt, standard error still reaches the terminal. This keeps warnings out of data files and out of pipes.
fn main() {
eprintln!("warning: {} items skipped", 2);
println!("result: ok");
}Run it with cargo run > out.txt. The warning appears on screen and out.txt contains only result: ok.
Standard error is not buffered, so each eprint! appears immediately. No flush is needed.
write! and writeln!: choose the writer
write! takes a destination as its first argument, then the usual format string. It calls the destination's write_fmt method and returns a Result. Two traits provide that method, and they are not interchangeable.
| Trait | Module | Error type | Typical targets |
|---|---|---|---|
| `Write` | `std::fmt` | `fmt::Error` | `String`, `Formatter` |
| `Write` | `std::io` | `io::Error` | `File`, `Stdout`, `Stderr`, `Vec<u8>` |
fmt::Write is for text. io::Write is for bytes and can fail for real reasons such as a closed pipe or a full disk.
Appending to a String
Bring fmt::Write into scope, and then a String can be the destination.
use std::fmt::Write;
fn main() -> Result<(), std::fmt::Error> {
let mut out = String::new();
write!(out, "{}+{}", 1, 2)?;
writeln!(out, " = {}", 1 + 2)?;
write!(out, "done")?;
println!("{out}");
Ok(())
}This prints two lines: 1+2 = 3 and done. Writing into a String cannot actually fail, but the signature still returns a Result, so you must handle it. Using ? is the usual way.
Writing to io destinations
With io::Write in scope, write! works on files, standard streams, and byte vectors.
use std::io::{self, Write};
fn main() -> io::Result<()> {
let mut buf: Vec<u8> = Vec::new();
writeln!(buf, "bytes: {}", 3)?;
println!("{} bytes written", buf.len());
let stdout = io::stdout();
let mut handle = stdout.lock();
for i in 1..=3 {
writeln!(handle, "line {i}")?;
}
handle.flush()?;
writeln!(io::stderr(), "this goes to stderr")?;
Ok(())
}The vector receives 9 bytes (bytes: 3 plus a newline). stdout.lock() takes the lock once, so a loop of writes does not lock and unlock on every line. That is useful for programs that print a lot of output.
Importing both traits
Two use lines that both import a trait named Write conflict, and the compiler reports error E0252. Rename one, or import it anonymously.
use std::fmt::Write as _;
use std::io::Write as _;
fn main() {
let mut s = String::new();
write!(s, "{}", 1).unwrap();
let mut v: Vec<u8> = Vec::new();
write!(v, "{}", 2).unwrap();
println!("{s} {}", v.len());
}The as _ form brings in the trait's methods without a usable name, which is all write! needs. This prints 1 1.
Missing import errors
If write!(s, ...) on a String fails with "cannot write into String" or "no method named write_fmt", the trait is not in scope. Add use std::fmt::Write;. The compiler's help text usually names the missing import.
Writing code that accepts any destination
A function that takes a generic writer works with a file, standard output, or an in-memory buffer. The buffer version is easy to test.
use std::io::{self, Write};
fn report<W: Write>(out: &mut W, items: &[(&str, u32)]) -> io::Result<()> {
for (name, qty) in items {
writeln!(out, "{name:<8}{qty:>4}")?;
}
Ok(())
}
fn main() -> io::Result<()> {
let items: [(&str, u32); 2] = [("apple", 3), ("pear", 12)];
report(&mut io::stdout(), &items)?;
let mut buf = Vec::new();
report(&mut buf, &items)?;
assert_eq!(
String::from_utf8(buf).unwrap(),
"apple 3\npear 12\n"
);
Ok(())
}The names are left-aligned in 8 columns and the quantities right-aligned in 4. The assert_eq! confirms the exact bytes written.
The same idea applies inside Display implementations. There, write!(f, ...) targets a Formatter, and the return type is fmt::Result. With several writes in a row, chain them with ? and end with Ok(()). Only the last expression's result is returned otherwise, and earlier errors are silently dropped.
Failure behavior
println! and eprintln! panic if writing fails, for example when output is piped to a program that has already exited. writeln!(io::stdout(), ...) returns the error instead, so you can handle it. Programs that are meant to be piped, such as command-line filters, often use writeln! for this reason.
Ignoring the Result from write! produces an unused_must_use warning. Handle it with ?, unwrap, or expect. Do not discard it with let _ = unless you have decided the failure does not matter.
Choosing a macro
- Need the text as a value? Use
format!. - Showing it to the user? Use
println!, oreprintln!for diagnostics. - Building a large string piece by piece? Use
write!on aString. - Writing to a file, socket, or buffer, or handling write errors? Use
write!orwriteln!withio::Write. - Implementing
DisplayorDebug? Usewrite!(f, ...).
Exercise
This program fails to compile with "no method named write_fmt found for struct String". What one-line change fixes it, and why does println!("{}", out) at the end not need that change?
use std::fmt;
fn main() -> Result<(), fmt::Error> {
let mut out = String::new();
write!(out, "{}", 42)?;
println!("{}", out);
Ok(())
}
Show answer
Add use std::fmt::Write;. write! calls the write_fmt method, which only exists on String when the fmt::Write trait is in scope. println! does not call a method on out. It writes to standard output and only reads out through Display, so no extra import is needed.
Exercise
A program prints its results with println! and its warnings with println! too. A user runs program > results.txt and finds warnings mixed into the file. Which macro should the warnings use, and what will the user see on screen and in the file after the fix?
Show answer
Use eprintln! for the warnings. The warnings then go to standard error, so they appear on the terminal. The file results.txt receives only the standard output text from println!.