concept Display in category rust

appears as: Display
Rust in Action

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 macros println!, print!, write!, writeln! and format! all rely on the Display and Debug traits. 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 Debug trait auto-implementations as a crutch, but what should you do if you wanted to provide custom text? Searching through rustdoc documentation, Display requires that types implement a fmt method that returns fmt::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
}