Rust有调试宏吗?



在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有类似的东西吗?

Rust 1.32.0

Rust 1.32.0稳定了dbg!()宏,输出:

  • 调用宏的文件名。
  • 调用宏的行号。
  • 参数的漂亮打印(必须实现Debug特性)。

注意: dbg!()移动其参数,因此您可能希望通过引用传递非复制类型。

示例:point (Playground)数组
#[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
    }
]
示例:条件编译(Playground)

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

在Rust 1.32.0之前

您可以使用日志箱,也可以自己定义一个。

虽然使用DK回答中提到的log crate之类的东西是有意义的,但这里是如何直接等效于您的问题:

// 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

您可以自己定义它们,但使用log crate会更简单,它为各种目的定义了几个宏(请参阅log文档)。

请注意,crate只提供前端用于日志记录;您还需要选择一个后端。在log文档中有一个基本的示例,或者您可以使用env_loggerlog4rs

基于Chris Emerson回答和CJ McAllister评论的宏

// Disable warnings
#[allow(unused_macros)]
// The debug version
#[cfg(debug_assertions)]
macro_rules! log {
    ($( $args:expr ),*) => { println!( $( $args ),* ); }
}
// Non-debug version
#[cfg(not(debug_assertions))]
macro_rules! log {
    ($( $args:expr ),*) => {()}
}
使用

log!("Don't be crazy");
log!("Answer is {}", 42);

cargo build --release将用单元元组();替换所有log!(...)

我没有找到替代的方法,但我认为编译器会这样做。

最新更新