Kocsis Dávid
Kocsis Dávid

Reputation: 549

Rust macro repetition with plus

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?

Upvotes: 4

Views: 1759

Answers (1)

SCappella
SCappella

Reputation: 10464

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)

Upvotes: 7

Related Questions