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.
use std::fmt::Write; let mut s = String::new(); write!(s, "{}-{}", 1, 2).unwrap();
Try it
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.
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
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 aStringfails with "no method namedwrite_fmt" unlessuse std::fmt::Write;is in scope. If you also importstd::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::Writefor bytes. AVec<u8>andstdout()implementio::Write, notfmt::Write. fmt::Errorhas no payload. Do not use it for real error reporting; custom sinks should record details themselves if they need them.- Inside
Displayimpls you receive&mut Formatter, sowrite!(f, ...)works there without an import becauseFormatterhas an inherentwrite_fmt. - Adapters. To print into something that only has
io::Write, wrap formatting inio::Write::write_fmtinstead; writing generic code over both needs two bounds. &mut Wis alsoWrite(blanket impl), so you can pass&mut sinkto functions takingimpl Writerepeatedly.ToStringalternative. For a one-off conversion useto_string(); for accumulating many pieces usefmt::Write.