如何在rust中调试结构

转载自个人网站:http://humblelei.com/posts/de...

在编写下面这段简短的代码时:

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

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

struct Student{
    name: String
}

我遇到一些错误:

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

幸运的是,rust 给了解决这个问题的一些提示:

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

最简单的是把 #[derive(Debug)]添加到Student结构上:

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

或者参考提示来手动实现 std::fmt::Debug特性:

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()
    }
}

分别测试了两种方式,可以正常打印结构。

你可能感兴趣的:(rust)