关于rust:如何在rust中调试结构

53次阅读

共计 756 个字符,预计需要花费 2 分钟才能阅读完成。

转载自集体网站: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()}
}

别离测试了两种形式,能够失常打印构造。

正文完
 0