2020-10-03 13:14:49
Rust lang で構造体をデバッグのためにいい感じにコンソール出力する
Rust lang で構造体をデバッグのためにいい感じにコンソール出力する
#[derive(Debug)]
を記載する
構造体を println!
マクロで出力するには構造体定義の直前で #[derive(Debug)]
という注釈を記載する必要があります。
println!
マクロでは指定子である {:?}
または {:#?}
を使う
指定子である {:#?}
を使うといい感じに出力してくれます。
コード
#[derive(Debug)]
struct Blogdetail {
id: u32,
title: String,
body: String,
created_at: String,
updated_at: String,
}
fn main() {
let blogdetail = Blogdetail {
id: 1,
title: String::from("sample title. "),
body: String::from("sample body. sample body. sample body. sample body. sample body. "),
created_at: String::from("2020-10-03 12:33:00"),
updated_at: String::from("2020-10-03 12:33:00"),
};
println!("構造体をコンソール出力します(1行で出力)。
{:?}
", blogdetail);
println!("構造体をコンソール出力します(いい感じに出力)。
{:#?}
", blogdetail);
}
実行結果
/home/nao000dotcom/structure # rustc main.rs
/home/nao000dotcom/structure # ./main
構造体をコンソール出力します(1行で出力)。
Blogdetail { id: 1, title: "sample title. ", body: "sample body. sample body. sample body. sample body. sample body. ", created_at: "2020-10-03 12:33:00", updated_at: "2020-10-03 12:33:00" }
構造体をコンソール出力します(いい感じに出力)。
Blogdetail {
id: 1,
title: "sample title. ",
body: "sample body. sample body. sample body. sample body. sample body. ",
created_at: "2020-10-03 12:33:00",
updated_at: "2020-10-03 12:33:00",
}
/home/nao000dotcom/structure #