Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust write! and writeln! macros

Reference for the Rust write! and writeln! macros: format into a String, a file, stdout or a Formatter, the two Write traits, errors and the unused Result.

write! and writeln! format their arguments like println!, but send the result to a destination you choose: a String, a Vec<u8>, a file, a socket, a locked stdout, or the Formatter inside a Display implementation. writeln! appends a newline.

The destination is the first argument and must have a write_fmt method. That comes from one of two traits: std::fmt::Write for text sinks such as String, and std::io::Write for byte sinks such as files. Both macros return the Result of the write, which you should handle or propagate.

Rust
use std::fmt::Write;
let mut s = String::new();
write!(s, "{}-{}", 1, 2).unwrap(); // s == "1-2"

Try it

Rust Writing into a String and a byte buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust write! inside Display and with errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
write!(dst, "format string", args...) -> fmt::Result   // dst: impl fmt::Write
write!(dst, "format string", args...) -> io::Result<()> // dst: impl io::Write
writeln!(dst, "format string", args...)
writeln!(dst)
Name Description
dst Expression with a write_fmt method: &mut String, &mut Vec<u8>, File, &mut Formatter, a stdout lock, ...
format string and args Same as for println!.

Returns: Result<(), fmt::Error> for text writers, Result<(), io::Error> for I/O writers.

Errors / panics / edge cases: a String never fails to be written to, but fmt::Write still returns a Result, so .unwrap() is common. I/O writers can fail (disk full, closed pipe, a fixed buffer that is too small). Ignoring the result triggers a #[must_use] warning.

Usage notes

  • Imports matter. Without use std::fmt::Write; or use std::io::Write; the call fails with "no method named write_fmt found". If you need both traits in one file, import one under an alias as in the first example.
  • dst is passed by mutable reference automatically: write!(s, ...) expands to s.write_fmt(format_args!(...)), so s must be mutable but you do not write &mut s.
  • Inside Display::fmt use write!(f, ...). The ? operator propagates fmt::Error; that error carries no detail, by design.
  • Efficiency: write! into an existing String avoids the temporary allocation that s.push_str(&format!(...)) makes.
  • Buffering: files and sockets are unbuffered; wrap them in BufWriter when making many small writes, and call flush() (or drop the writer) to get the data out.
  • Unwrapping: it is reasonable to unwrap() writes to a String or Vec<u8>, which cannot fail, but not writes to files or network streams.
  • writeln!(dst) with no format string writes only a newline.
  • Line endings are always \n, even on Windows.