Printing and debug-printing simple struct



examples/struct/struct-cannot-be-printed/src/main.rs
#[allow(dead_code)]

struct Red(i32);

fn main() {
    #[allow(unused_variables)]
    let red = Red(10);
    println!("{}", red.0);

    // println!("{}", red);
    // `Red` doesn't implement `std::fmt::Display`

    // println!("{:?}", red);
    //  `Red` doesn't implement `Debug`
}

examples/struct/struct-with-debug/src/main.rs
#![allow(dead_code)]

#[derive(Debug)]
struct Red(i32);

fn main() {
    let red = Red(10);
    //println!("{}", red);  // `Red` doesn't implement `std::fmt::Display`
    println!("{:?}", red); //  Red(10)
}

Red(10)


examples/struct/struct-with-display/src/main.rs
#[derive(Debug)]
struct Red(i32);

impl std::fmt::Display for Red {
    fn fmt(&self, format: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(format, "{}", self.0)
    }
}

fn main() {
    let red = Red(10);
    println!("{}", red); // 10
    println!("{:?}", red); //  Red(10)
}

10
Red(10)