Rust有调试宏吗?

use*_*741 8 debugging debug-print 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
Run Code Online (Sandbox Code Playgroud)

Rust有类似的东西吗?

Obl*_*ion 11

Rust 1.32.0

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);
}
Run Code Online (Sandbox Code Playgroud)

节目输出

[src/main.rs:14] &points = [
    Point {
        x: 0,
        y: 0
    },
    Point {
        x: 2,
        y: 3
    },
    Point {
        x: 5,
        y: 7
    }
]
Run Code Online (Sandbox Code Playgroud)

示例:条件编译(游乐场)

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

程序输出(调试模式)

---------------------Standard Error-----------------------

[src/main.rs:13] x = 4
[src/main.rs:14] x == 5 = false

---------------------Standard Output----------------------

x != 5
Run Code Online (Sandbox Code Playgroud)

程序输出(释放模式)

---------------------Standard Output----------------------

x != 5
Run Code Online (Sandbox Code Playgroud)

在Rust 1.32.0之前

您可以使用日志包,也可以自己定义.


DK.*_*DK. 8

你可以自己定义它们,但它是易于使用的log箱子,它定义了用于各种目的的几个宏(见log文档).

请注意,crate只提供日志记录的前端 ; 你还需要选择一个后端.log文档中有一个基本的例子,或者你可以使用env_logger或者类似的东西log4rs.


Chr*_*son 5

虽然使用像logDK的答案中提到的像箱子这样的东西是有意义的,但这里是如何直接等同于你的要求:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

在你的Cargo.toml,添加一[features]节:

[features]
my_debug = []
Run Code Online (Sandbox Code Playgroud)

然后输出显示cargo run --features my_debug,而不是普通cargo run.

  • 通过piggy带控制诸如debug_assert!之类的宏的现有`debug_assertions`属性,可以使代码更加简洁。只需将## cfg(feature =“ my_debug”)]位更改为## cfg(debug_assertions)],然后将更改更改为Cargo.toml。这样,对于发布版本,调试代码将被自动忽略! (2认同)