Skip to content

Instantly share code, notes, and snippets.

@barseghyanartur
Last active February 2, 2023 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barseghyanartur/60c96710241c4f9a436c964cd312cac9 to your computer and use it in GitHub Desktop.
Save barseghyanartur/60c96710241c4f9a436c964cd312cac9 to your computer and use it in GitHub Desktop.
Debug struct in Rust

Debug struct in Rust

Problem

This will not work

struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {
    let user = User {
        active: true,
        username: String::from("someusername123"),
        email: String::from("someone@example.com"),
        sign_in_count: 1,
    };
    dbg!(user);
}

Solution

This will work

#[derive(Debug)]
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {
    let user = User {
        active: true,
        username: String::from("someusername123"),
        email: String::from("someone@example.com"),
        sign_in_count: 1,
    };
    dbg!(user);
}

Alternatively, you could fine tune it by replacing the #[derive(Debug)] with the following:

impl fmt::Debug for User {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
      f.debug_struct("Point")
        .field("active", &self.active)
        .field("username", &self.username)
        .field("email", &self.email)
        .field("sign_in_count", &self.sign_in_count)
        .finish()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment