Search code examples
rustmacrosrust-macros

How to get both name and value of variable in a 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

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);
    }