pu369com

rust之#[derive(Debug)]

参考:https://rust-by-example.budshome.com/hello/print/print_debug.html

cargo new hello

main.rs

#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}

fn main() {
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };

    // 美化打印
    println!("{:#?}", peter);
}

如果去掉第一行#[derive(Debug)],IDE提示

`Person<'_>` doesn't implement `std::fmt::Debug`
 
`Person<'_>` cannot be formatted using `{:?}`
 
help: the trait `std::fmt::Debug` is not implemented for `Person<'_>`
note: add `#[derive(Debug)]` or manually implement `std::fmt::Debug`
note: required by `std::fmt::Debug::fmt`rustc(E0277)
main.rs(13, 23): `Person<'_>` cannot be formatted using `{:?}`
 
#[derive(Debug)] 这个`derive` 属性会自动创建所需的实现,使限定的`struct` 能使用 `fmt::Debug` 打印。

posted on 2021-08-18 16:29  pu369com  阅读(2565)  评论(0编辑  收藏  举报

导航