All types which want to be printable must implement the `std::fmt` formatting trait: `std::fmt::Debug` or `std::fmt::Display`.
Automatic implementations are only provided for types such as in the `std` library. All others have to be manually implemented.
## Debug
The implementation of `Debug` is very straightfoward: All types can `derive` the `std::fmt::Debug` implementation. This is not true for `std::fmt::Display` which must be manually implemented.
`{:?}` must be used to print out the type which has implemented the `Debug` trait.
```rust
// This structure cannot be printed either with `fmt::Display` or
// with `fmt::Debug`.
struct UnPrintable(i32);
// To make this struct printable with `fmt::Debug`, we can derive the automatic implementations provided by Rust
#[derive(Debug)]
struct DebugPrintable(i32);
```
1. π
```rust,editable
/* Fill in the blanks and Fix the errors */
struct Structure(i32);
fn main() {
// Types in std and Rust have implemented the fmt::Debug trait
println!("__ months in a year.", 12);
println!("Now __ will print!", Structure(3));
}
```
2. ππ So `fmt::Debug` definitely makes one type printable, but sacrifices some elegance. Maybe we can get more elegant by replacing `{:?}` with something else( but not `{}` !)
```rust,editable
#[derive(Debug)]
struct Person {
name: String,
age: u8
}
fn main() {
let person = Person { name: "Sunface".to_string(), age: 18 };
/* Make it output:
Person {
name: "Sunface",
age: 18,
}
*/
println!("{:?}", person);
}
```
3. ππ We can also manually implement `Debug` trait for our types
```rust,editable
#[derive(Debug)]
struct Structure(i32);
#[derive(Debug)]
struct Deep(Structure);
fn main() {
// The problem with `derive` is there is no control over how
// the results look. What if I want this to just show a `7`?
Implementing `fmt::Display` for a structure whose elements must be handled separately is triky. The problem is each `write!` generates a `fmt::Result` which must be handled in the same place.
Fortunately, Rust provides the `?` operator to help us eliminate some unnecessary codes for deaing with `fmt::Result`.