Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get both name and value of variable in Rust macro

Is it possible to make a rust macro that can access both the name and value of a variable passed as a parameter?

let my_variable: i32 = 5;
printvar!(my_variable); // => to print "my_variable = 5"

For example with C macros we can use the # operator:

#include <stdio.h>

#define PRINT_VAR(x) printf("%s = %d\n", #x, x);

 int main() {
    int my_variable = 5;
    PRINT_VAR(my_variable);
}
$ ./a.out
my_variable = 5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The equivalent of # in Rust is the stringify! macro:

macro_rules! print_var {
    ($var: ident) => {
        println!("{} = {}", stringify!($var), $var);
    }
}

fn main() {
    let my_variable = 5;
    // prints my_variable = 5
    print_var!(my_variable);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading