Pass an entire macro to another macro
I'm trying to make a simple macro that calls vec!
with what it receives and then does some simple processing before returning a new vector:
macro_rules! sorted_vec {
($x:expr) => {
{
let v = vec![$x];
v.sort();
v
}
}
}
The problem is my macro is trying to parse the syntax, so it complains about commas, etc. It makes sense, but I'm not sure how to get around it. I don't think which expr
is the correct fragment specifier to use. How do I get it to pass the original input to vec!
without processing it?
source to share
A fragment specifier tt
(Token-Tree) is required . A tt
is just an arbitrary valid rust marker, like a keyword or statement, or a bracket / block / square bracket with an arbitrary one tt
inside. Combined with a variable macro, you get infinite tokens that can be directly passed to another macro
macro_rules! sorted_vec {
($($x:tt)*) => {
{
let mut v = vec![$($x)*];
v.sort();
v
}
}
}
source to share