I'm trying to make a simple macro that invokes vec!
with whatever it receives then does some simple processing before returning the new vector:
macro_rules! sorted_vec {
($x:expr) => {
{
let v = vec![$x];
v.sort();
v
}
}
}
The problem is that my macro is trying to parse the syntax, so it complains about commas, etc. That makes sense, but I'm not sure how to get around it. I don't think expr
is the correct fragment specifier to use. How do I get it to pass the raw input on to vec!
without processing it?
The fragment specifier you want is tt
(Token-Tree). A tt
is simply an arbitrary valid rust-token like a keyword or an operator or a bracket/block/square-bracket with arbitrary tt
s inside. Combined with a variadic 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
}
}
}
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