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.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。