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.
use std::fmt::Write; let mut s = String::new(); write!(s, "{}-{}", 1, 2).unwrap(); // s == "1-2"
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
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;oruse std::io::Write;the call fails with "no method namedwrite_fmtfound". If you need both traits in one file, import one under an alias as in the first example. dstis passed by mutable reference automatically:write!(s, ...)expands tos.write_fmt(format_args!(...)), sosmust be mutable but you do not write&mut s.- Inside
Display::fmtusewrite!(f, ...). The?operator propagatesfmt::Error; that error carries no detail, by design. - Efficiency:
write!into an existingStringavoids the temporary allocation thats.push_str(&format!(...))makes. - Buffering: files and sockets are unbuffered; wrap them in
BufWriterwhen making many small writes, and callflush()(or drop the writer) to get the data out. - Unwrapping: it is reasonable to
unwrap()writes to aStringorVec<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.
Related
println!,format!,Display,String- Lessons: Display and From, IO traits, Files and IO