Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust have a debug macro?

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?

like image 208
user3384741 Avatar asked Jul 01 '16 08:07

user3384741


1 Answers

Rust 1.32.0

Rust 1.32.0 stabilized the dbg!() macro, which outputs:

  • The file name on which the macro was called.
  • The line number on which the macro was called.
  • A pretty print of the argument (which must implement the Debug trait).

Note: dbg!() moves its argument, so you may want to pass non-copy types by reference.

Example: Array of Points (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);
}

Program Output

[src/main.rs:14] &points = [
    Point {
        x: 0,
        y: 0
    },
    Point {
        x: 2,
        y: 3
    },
    Point {
        x: 5,
        y: 7
    }
]

Example: Conditional Compilation (Playground)

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

Before Rust 1.32.0

You could use the log crate or you could define one yourself.

like image 117
ObliqueMotion Avatar answered Oct 08 '22 16:10

ObliqueMotion