Misc 7 @Kivooeo
Warning: this quiz is still "work-in-progress", some questions might not have good explanations (or any at all), formatting/structure/titles/etc are not final, and so on. You might want to return here on a later date.
macro_rules! capture {
($e:expr) => {
transform!($e)
};
}
macro_rules! transform {
($a:tt + $b:tt) => {
$a * $b
};
($other:expr) => {
$other
};
}
fn main() {
let x = capture!(2 + 3);
println!("{}", x); // what this will print?
}
Solution
It will prints 5.
Once a token is captured as an expression (:expr), it becomes opaque to macro pattern matching and cannot be destructured into its component tokens.
When capture!(2 + 3) is invoked, the $e:expr matcher captures 2 + 3 as a single expression token tree. This captured expression is then passed to transform!($e), which attempts to match it against the pattern $a:tt + $b:tt.
However, because $e was already captured as an :expr, it cannot be pattern-matched as separate tokens anymore. The first arm $a:tt + $b:tt fails to match, so the second arm $other:expr matches instead, and the expression 2 + 3 is returned as-is, evaluating to 5.