Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print both an expression and its value in Rust?

Is there a way of doing this?

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

Output:

self.mega_ultra_field 100500
like image 955
hedgar2017 Avatar asked Aug 11 '18 20:08

hedgar2017


1 Answers

Premade solution

Use dbg!:

dbg!(self.mega_ultra_field);
[src/main.rs:16] self.mega_ultra_field = 100500

Writing your own

Use stringify!:

macro_rules! print_expr_and_value {
    ($e:expr) => {
        eprintln!("{} {}", 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);

        dbg!(self.mega_ultra_field);
    }
}

fn main() {
    Foo {
        mega_ultra_field: 0,
    }
    .bar();
}
self.mega_ultra_field 100500
like image 169
Shepmaster Avatar answered Sep 30 '22 17:09

Shepmaster