Printing is handle by a series of macros defined in std::fmt some of which include:
format!: write formatted text to String
print!: print fotmatted text to the console(io::stdout)
println!: same as print! but a newline is appended
eprint : same as format!, but the text if printed to the santard error(io::stderr)
eprintln: smae as eprint, but a newline is appended
std::fmt contains many traits which govern the display of text. The base form of two important ones are listed below:
fmt::Debug: Uses the {:?} marker. Format text for debugging purpoes
fmt::Display: Uses the {} marker. Format text in a more elegant, user friendly fashion.
Note: Implementing the fmt::Display trait automatically implements the ToString trait which allows us to convert the type to String.
Debug
All types which want to use std::fmt formatting traits require an implementation to be printable. Automatic implementations are only provided for types such as in the std library. All others must be* maually* implemented somehow.
All types can derive(automatically create) the fmt::Debug implementation. This is not true for fmt::Display which must be manually implemented.
1 2 3 4 5 6 7
// cannot be printed either with `fmt::Display` or with `fmt::Debug` structUnPrintable(i32);
// The `derive` attribute automatically creates the implementation // required to make this `struct` printable with `fmt::Debug` #[derive(Debug)] structDebugUnPrintable(i32);
fmt::Debug definitely makes this printable but scarifices some elegance.Rust also provides pretty printing with {:#?}
One can manually implemnet fmt::Debug instead of derive.
implfmt::Display forTestDisplay { fnfmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Write strictly the two elements into the supplied output // stream: `f`. Returns `fmt::Result` which indicates whether the // operation succeeded or failed. Note that `write!` uses syntax which // is very similar to `println!`. write!(f, "TestDebug: {} {}", self.v1, self.v2) } }
fnmain() { lett = TestDisplay::new(1, 2); println!("{}", t); }
output
1 2 3 4
Compiling display_manually v0.1.0 (/home/readlnh/workspace/rust_workspace/rust-by-example/display_manually) Finished dev [unoptimized + debuginfo] target(s) in 0.28s Running `target/debug/display_manually` TestDebug: 1 2
implfmt::Display forList { fnfmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Extract the value using the type indexing letvec = &self.0; write!(f, "[")?;
for (index, v) in vec.iter().enumerate() { if index != 0 { write!(f, ", ")?; } write!(f, "{}: {}", index, v)?; } write!(f, "]") } }