In C++, I use something like this DEBUG
macro:
#ifdef DEBUG
#define DEBUG_STDERR(x) (std::cerr << (x))
#define DEBUG_STDOUT(x) (std::cout << (x))
#else
#define DEBUG_STDERR(x)
#define DEBUG_STDOUT(x)
#endif
Does Rust have something similar?
Although it makes sense to use something like the log
crate as mentioned in DK's answer, here's how to do the direct equivalent of what you asked:
// The debug version
#[cfg(feature = "my_debug")]
macro_rules! debug_print {
($( $args:expr ),*) => { println!( $( $args ),* ); }
}
// Non-debug version
#[cfg(not(feature = "my_debug"))]
macro_rules! debug_print {
($( $args:expr ),*) => {}
}
fn main() {
debug_print!("Debug only {}", 123);
}
And in your Cargo.toml
, add a [features]
section:
[features]
my_debug = []
The output then appears with cargo run --features my_debug
, and doesn't with a plain cargo run
.