Reprinted from personal website: http://humblelei.com/posts/debug-struct.html

When writing the following short code:

 fn main() {
    let student = Student{
        name: "李寻欢".to_string()
    };

    println!("{:?}", student);
}

struct Student{
    name: String
}

I get some errors:

 error[E0277]: `Student` doesn't implement `Debug`
 --> src\main.rs:6:22
  |
6 |     println!("{:?}", student);
  |                      ^^^^^^^ `Student` cannot be formatted using `{:?}`

Luckily, rust gives some hints for solving this problem:

 = help: the trait `Debug` is not implemented for `Student`
= note: add `#[derive(Debug)]` to `Student` or manually `impl Debug for Student`

The easiest is to add #[derive(Debug)] to the Student structure:

 #[derive(Debug)]
struct Student{
    name: String
}

Or refer to the tips to manually implement the std::fmt::Debug feature:

 use std::fmt::{Debug, Formatter, Result};

struct Student{
    name: String
}

impl Debug for Student {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        f.debug_struct("Student")
         .field("name", &self.name)
         .finish()
    }
}

Two methods were tested respectively, and the structure can be printed normally.


小邓
125 声望176 粉丝