How can the + operator be used as a repetition separator?
fn dot(self, rhs: Self) -> S {
$(self.$s * rhs.$s)++
}
$s will be x, y, z, so I would like the macro to exapnd to self.x * rhs.x + self.y * rhs.y + self.z * rhs.z. If I write $(self.$s * rhs.$s)-+, then it works and expands to subtractions, but I need additions, is it possible to escape the + token?
Unfortunately, this isn't directly possible (as of rustc 1.41). The workaround mentioned at that issue is to put the plus before every item in the repetition and have a separate macro that strips off the extra plus at the front.
macro_rules! strip_plus {
(+ $($rest: tt)*) => {
$($rest)*
}
}
It's used like this:
macro_rules! sum_all {
($($items: tt)+) => {
strip_plus!($(+ $items)+)
}
}
fn main() {
assert_eq!(sum_all!(1 2 3 4 5), 15);
}
(playground)
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