Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 427
JShorthouse Avatar asked Dec 10 '25 04:12

JShorthouse


1 Answers

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);
}
like image 89
Aplet123 Avatar answered Dec 11 '25 21:12

Aplet123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!