概要
バイナリクレートを開発していて、デバッグ等の特定条件上でのみprintln!
を用いたい時がある。そのような際は、debug-assersion
を用いる。
手法
1. cargo.toml の追記
cargo.toml
にて、以下を追記する。
[profile.dev]
debug-assertions = true
[profile.dev]
は、デフォルトの cargo run コマンドに適用されるprofile設定。debug-assertions
の真偽値によって、表示するべきか、そうでないかが決定される。
2. #[cfg(debug_assertions)] の挿入
main.rsにて、以下のように条件に応じて表示切替を行いたいprintlnの上に#[cfg(debug_assertions)]
を挿入。
#[cfg(debug_assertions)]
println!("debug print");
まとめ
上記により、デバッグで何かしらの値を表示させたいときはcargo.toml
にてdebug-assertions
をいじればよい。もしかしたら、dbg_println!
みたいなcfg(debug_assetions)
がprintln
に組み込まれたマクロが既にあるかもしれない。適宜調査を行う。