concept Display in category rust
appears as: Display

This is an excerpt from Manning's book Rust in Action.
3.6.2. Implementing Display for your own types
println!and a number of others live within a family of macros that all use the same underlying machinery. The macrosprintln!,print!,write!,writeln!andformat!all rely on theDisplayandDebugtraits. That is, they rely on trait implementations provided by programmers to be able to convert from{}to what is printed to the console.
It’s possible to rely on the
Debugtrait auto-implementations as a crutch, but what should you do if you wanted to provide custom text? Searching through rustdoc documentation,Displayrequires that types implement afmtmethod that returnsfmt::Result.Listing 3. 19. Implementing Display for File and its associated type FileState
impl Display for FileState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { } } } impl Display for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}.{}.{}.{}", self.0, self.1, self.2, self.3) } }Listing 3. 20. Working code snippet to implement Display for a struct that includes fields that also need to implement Display (ch3/ch3-implementing-display.rs)
#![allow(dead_code)] #1 use std::fmt; #2 use std::fmt::{Display}; #3 #[derive(Debug,PartialEq)] enum FileState { Open, Closed, } #[derive(Debug)] struct File { name: String, data: Vec<u8>, state: FileState, } impl Display for FileState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { FileState::Open => write!(f, "OPEN"), #4 FileState::Closed => write!(f, "CLOSED"), #4 } } } impl Display for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<{} ({})>", self.name, self.state) #5 } } impl File { fn new(name: &str) -> File { File { name: String::from(name), data: Vec::new(), state: FileState::Closed } } } fn main() { let f6 = File::new("f6.txt"); //... println!("{:?}", f6); #6 println!("{}", f6); #7 }