Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Printing and debug-printing simple struct

#[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`
}
#![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)
#[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)