Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The fmt::Write trait

Reference for Rust std::fmt::Write: write! and writeln! into a String, write_str and write_char, how it differs from io::Write, and implementing it for custom sinks.

std::fmt::Write is the trait for destinations that accept text (UTF-8 str). Its main use is write! and writeln! on a String, which formats straight into the existing buffer instead of creating temporary strings with format!. It has one required method, write_str, and provides write_char and write_fmt on top.

Do not confuse it with std::io::Write, which writes bytes to files, sockets and stdout and can fail with I/O errors. fmt::Write works on text only and its error type, fmt::Error, carries no detail.

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

Try it

Rust Building a string with write! and writeln!

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 A custom sink with a size limit

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
pub trait Write {
    fn write_str(&mut self, s: &str) -> fmt::Result;
    fn write_char(&mut self, c: char) -> fmt::Result { /* provided */ }
    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result { /* provided */ }
}

write!(dest, "format {}", value)    // calls dest.write_fmt(format_args!(...))
writeln!(dest, "format {}", value)  // adds a newline
Name Description
write_str(&mut self, s) The only required method. Appends the text.
write_char Appends one char; default encodes it and calls write_str.
write_fmt Called by write!; formats the arguments into the sink.

Returns: Result<(), fmt::Error>.

Errors / panics / edge cases: String never returns an error (it panics only if memory is exhausted), so .unwrap() is safe there. Custom sinks can return Err(fmt::Error) to abort formatting. Formatter also implements fmt::Write, which is how Display impls write.

Usage notes

  • Import the trait. write!(s, ...) on a String fails with "no method named write_fmt" unless use std::fmt::Write; is in scope. If you also import std::io::Write, rename one: use std::fmt::Write as _;.
  • Prefer it over format! in loops. s += &format!(...) allocates a temporary each time; write!(s, ...) appends directly.
  • Text only. Use io::Write for bytes. A Vec<u8> and stdout() implement io::Write, not fmt::Write.
  • fmt::Error has no payload. Do not use it for real error reporting; custom sinks should record details themselves if they need them.
  • Inside Display impls you receive &mut Formatter, so write!(f, ...) works there without an import because Formatter has an inherent write_fmt.
  • Adapters. To print into something that only has io::Write, wrap formatting in io::Write::write_fmt instead; writing generic code over both needs two bounds.
  • &mut W is also Write (blanket impl), so you can pass &mut sink to functions taking impl Write repeatedly.
  • ToString alternative. For a one-off conversion use to_string(); for accumulating many pieces use fmt::Write.