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

macros, rust

Solution

You want `stringify!`:

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

fn main() {
    str_var!(foo);
    println!("foo: {:?}", foo);
}

Problem

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.

Original source