在C ++中,我使用类似这样的DEBUG
宏:
#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
Rust有类似的东西吗?
虽然使用像DK的答案中提到的log
箱子这样的东西是有意义的,但这里是如何直接等同于你的要求:
// 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);
}
在你的Cargo.toml
,添加一个[features]
部分:
[features]
my_debug = []
然后输出与cargo run --features my_debug
一起出现,并且不与简单的cargo run
一起出现。
Rust 1.32.0稳定了dbg!()
宏,其输出:
Debug
特征)。注意:dbg!()
移动其参数,因此您可能希望通过引用传递非复制类型。
#[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);
}
节目输出
[src/main.rs:14] &points = [
Point {
x: 0,
y: 0
},
Point {
x: 2,
y: 3
},
Point {
x: 5,
y: 7
}
]
OP表示希望仅在调试模式下编译时显示调试内容。
以下是实现此目的的方法:
#[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");
}
}
程序输出(调试模式)
---------------------Standard Error-----------------------
[src/main.rs:13] x = 4
[src/main.rs:14] x == 5 = false
---------------------Standard Output----------------------
x != 5
程序输出(释放模式)
---------------------Standard Output----------------------
x != 5
你可以自己定义它们,但是使用log
crate会更简单,它可以为各种目的定义几个宏(参见the log
documentation)。
请注意,crate只提供日志记录的前端;你还需要选择一个后端。在log
文档中有一个基本的例子,或者你可以使用像env_logger
或log4rs
这样的东西。