Sub topic 13
format!, eprintln!, write!, and friends
This chapter assumes you know println! placeholders, the Display and Debug traits, and the basics of Result. Every macro below uses the same format-string syntax you have already seen. They differ in where the text goes.
Choosing a destination
| Macro | Destination | Returns |
|---|---|---|
| `print!`, `println!` | standard output | `()` |
| `eprint!`, `eprintln!` | standard error | `()` |
| `format!` | a new `String` | `String` |
| `write!`, `writeln!` | any writer you provide | `Result` |
The ln variants add a newline. Without it, print! output may not appear until the line buffer is flushed.
format! builds a String
format! works like println! but returns the text instead of printing it. Use it when you need the text as a value, for example to pad a label or to pass a message to another function.
eprintln! keeps diagnostics out of the data stream
Standard error is a separate stream from standard output. If a user runs mytool > out.txt, only standard output goes to the file. Errors and progress messages written with eprintln! still appear in the terminal.
fn main() {
println!("{{}} prints braces; value = {{{}}}", 5);
eprintln!("warning: {}", "written to stderr");
let label = format!("{:>5}", 1);
println!("[{label}]");
let doubled = dbg!(21 * 2);
println!("{doubled}");
}The first line prints {} prints braces; value = {5}. The label line prints [ 1]. dbg! writes the expression, its value, and the file and line to standard error. It then returns the value, so doubled is 42.
write! and writeln! target any writer
write! takes a destination as its first argument and calls that destination's write_fmt method. The result is a Result that you must handle. Which trait you import decides which destinations work:
std::fmt::Writecovers text targets such asString. The error type isfmt::Error.std::io::Writecovers byte targets such as files, sockets, and stdout. The error type isio::Error.
use std::fmt::Write as _;
use std::io::{self, Write as _};
fn main() -> io::Result<()> {
let mut s = String::new();
write!(s, "{}-{}", 1, 2).unwrap();
writeln!(s, "!").unwrap();
let mut out = io::stdout().lock();
writeln!(out, "{s}")?;
Ok(())
}The program prints 1-2! followed by a blank line. s already ends with a newline, and writeln! adds a second one. Writing to a String cannot really fail, so unwrap() is acceptable there. Writing to stdout can fail, for example when the pipe is closed, so the example uses ?.
Import both traits with as _. This brings the methods into scope without a name clash. The compiler picks the right write_fmt from the type of the first argument.
Inside a Display implementation
The f argument in fmt(&self, f: &mut Formatter) is also a writer. This is why write!(f, "({}, {})", self.x, self.y) works in a Display implementation. The ? operator is often used there to chain several writes:
use std::fmt;
struct Pair(i32, i32);
impl fmt::Display for Pair {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "<")?;
write!(f, "{}", self.0)?;
write!(f, ", {}>", self.1)
}
}
fn main() {
println!("{}", Pair(3, 4));
}This prints <3, 4>.
Exercise
You run mytool > report.txt. Your program calls println!("data") and eprintln!("working..."). What ends up in report.txt, and what shows in the terminal?
Show answer
report.txt contains data, because println! writes to standard output, which the shell redirected. The terminal shows working..., because eprintln! writes to standard error, which was not redirected.