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.
You want stringify!
:
macro_rules! str_var {
($name:ident) => {
let $name = String::from(stringify!($name));
};
}
fn main() {
str_var!(foo);
println!("foo: {:?}", foo);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With