Specs:
- Rust nightly build 1.53.0
- unstringify! crate dependency https://docs.rs/unstringify/0.1.1/unstringify/macro.unstringify.html
I am building a simple macro to call an attribute on a struct when the attribute's name is passed in as a string, like so:
send!(struct, "title"); // => struct.title
Works
So far the above code works, because "title" is entered in as a verbatim string literal. But to be useful I want to pass in a my_str
identifier for a string literal and have it be treated like the string literal I passed in above (basically like how things work in a normal function).
let my_str = "title";
send!(struct, my_str); // => struct.title
Doesn't Work
The code above gives me this error:
expected a string literal, a verbatim
stringify!
call, or a verbatimconcat!
call.
Here is the code for the send! macro I created.
macro_rules! send {
($obj:ident, $msg:expr) => {
unstringify!(
let $x = unstringify!($msg) in {
$obj . $x
}
)
}
}
If the above code looks confusing let me explain. It is saying call unstringify! on $msg
and assign to $x
then output $obj . $x
as the final result. It is NOT two unstringify! calls (refer to the unstringify! reference material for any questions on that)
I know other macros like Rust's println!
macro can handle either literals passed in or variables and treats them as the same. How can I achieve this in the send! macro?