Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust macro repetition with plus

Tags:

rust

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?

like image 256
Kocsis Dávid Avatar asked Oct 22 '25 05:10

Kocsis Dávid


1 Answers

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)

like image 154
SCappella Avatar answered Oct 24 '25 11:10

SCappella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!