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` 打印。
原文地址:https://www.cnblogs.com/pu369/p/15157402.html