如何在Rust中同时打印表达式及其值?

时间:2018-08-11 20:13:28

标签: debugging logging reflection macros rust

有没有办法做到这一点?

self.mega_ultra_field = 100500;
print_expr_and_value!(self.mega_ultra_field);

输出:

self.mega_ultra_field 100500

1 个答案:

答案 0 :(得分:8)

通过stringify!

macro_rules! print_expr_and_value {
    ($e:expr) => {
        println!("{} {}", stringify!($e), $e)
    };
}
struct Foo {
    mega_ultra_field: i32,
}

impl Foo {
    fn bar(&mut self) {
        self.mega_ultra_field = 100500;
        print_expr_and_value!(self.mega_ultra_field);
    }
}

fn main() {
    Foo {
        mega_ultra_field: 0,
    }.bar();
}