write in std - Rust (original) (raw)
Macro std::write
macro_rules! write {
($dst:expr, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span></span></span></span>arg:tt)*) => { ... };
}
Expand description
Writes formatted data into a buffer.
This macro accepts a ‘writer’, a format string, and a list of arguments. Arguments will be formatted according to the specified format string and the result will be passed to the writer. The writer may be any value with a write_fmt
method; generally this comes from an implementation of either the fmt::Write or the io::Write trait. The macro returns whatever the write_fmt
method returns; commonly a fmt::Result, or anio::Result.
See std::fmt for more information on the format string syntax.
use std::io::Write;
fn main() -> std::io::Result<()> {
let mut w = Vec::new();
write!(&mut w, "test")?;
write!(&mut w, "formatted {}", "arguments")?;
assert_eq!(w, b"testformatted arguments");
Ok(())
}
A module can import both std::fmt::Write
and std::io::Write
and call write!
on objects implementing either, as objects do not typically implement both. However, the module must import the traits qualified so their names do not conflict:
use std::fmt::Write as FmtWrite;
use std::io::Write as IoWrite;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut s = String::new();
let mut v = Vec::new();
write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
assert_eq!(v, b"s = \"abc 123\"");
Ok(())
}
Note: This macro can be used in no_std
setups as well. In a no_std
setup you are responsible for the implementation details of the components.
use core::fmt::Write;
struct Example;
impl Write for Example {
fn write_str(&mut self, _s: &str) -> core::fmt::Result {
unimplemented!();
}
}
let mut m = Example{};
write!(&mut m, "Hello World").expect("Not written");