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?
Rust 1.32.0 stabilized the dbg!()
macro, which outputs:
Debug
trait).Note: dbg!()
moves its argument, so you may want to pass non-copy types by reference.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let points = [
Point { x: 0, y: 0 },
Point { x: 2, y: 3 },
Point { x: 5, y: 7 },
];
dbg!(&points);
}
Program Output
[src/main.rs:14] &points = [
Point {
x: 0,
y: 0
},
Point {
x: 2,
y: 3
},
Point {
x: 5,
y: 7
}
]
The OP expressed a desire to display the debug content only when compiling in debug mode.
The following is a way to achieve this:
#[cfg(debug_assertions)]
macro_rules! debug {
($x:expr) => { dbg!($x) }
}
#[cfg(not(debug_assertions))]
macro_rules! debug {
($x:expr) => { std::convert::identity($x) }
}
fn main() {
let x = 4;
debug!(x);
if debug!(x == 5) {
println!("x == 5");
} else {
println!("x != 5");
}
}
Program Output (Debug Mode)
---------------------Standard Error-----------------------
[src/main.rs:13] x = 4
[src/main.rs:14] x == 5 = false
---------------------Standard Output----------------------
x != 5
Program Output (Release Mode)
---------------------Standard Output----------------------
x != 5
You could use the log crate or you could define one yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With