Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Rust macro to define a String variable with the value of its own identifier?

Tags:

macros

rust

I want to write a macro to define something like below:

let FOO: String = "FOO".to_string();

It is possible for me to have a macro:

macro_rules! my_macro {
    ($name: ident, $val: expr) => {
        let $name: String = $val.to_string();
    }
}

and use it as my_macro!(FOO, "FOO");

However, this is a bit redundant. I expect to have something like my_macro!(FOO), and it can expand and use the $name as identifier, but also in the string value.

like image 507
qinsoon Avatar asked Oct 31 '16 06:10

qinsoon


1 Answers

You want stringify!:

macro_rules! str_var {
    ($name:ident) => {
        let $name = String::from(stringify!($name));
    };
}

fn main() {
    str_var!(foo);
    println!("foo: {:?}", foo);
}
like image 152
DK. Avatar answered Oct 27 '22 22:10

DK.