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` 打印。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2026 CODEPRJ.COM