調試輸出Struct
在開發過程中,很多時候會想要查看某個struct實例中的數據,但直接輸出是不行的:
struct Person{ name: String, age: i32, } fn main(){ let p = Person{ name: String::from("junmajinlong"), age: 23, }; // 直接輸出p會報錯 println!("{}", p); }
這時需要在struct Person
前加上#[derive(Debug)]
,然後使用{:?}
或{:#?}
進行調試輸出。
#[derive(Debug)] struct Person{ name: String, age: i32, } fn main(){ let p = Person{ name: String::from("junmajinlong"), age: 23, }; println!("{:?}", p); println!("{:#?}", p); }
輸出結果:
Person { name: "junmajinlong", age: 23 }
Person {
name: "junmajinlong",
age: 23,
}