qinsoon
qinsoon

Reputation: 1493

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

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.

Upvotes: 14

Views: 6843

Answers (1)

DK.
DK.

Reputation: 59135

You want stringify!:

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

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

Upvotes: 23

Related Questions