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-2025 CODEPRJ.COM