Difficulty writing binary operation macro

I'm attempting to write a macro that performs binary operations. It is defined as follows:

macro_rules! binary_op {
    ($x:expr, $op:tt, $y:expr) => {
        {$x $op $y}
    };
}

I intend to use it in the following function:

fn do_binary_op(&mut self, op: char) {
    match op {
        '+' | '-' | '*' | '/' => {
            let left = self.pop(); // returns an f64 from this object's stack
            let right = self.pop();

            self.push(binary_op!(left, op, right));
        },
     ...
    }
}

My intention is to have the binary_op! macro expand to something like 1 + 1, however the compiler complains that rather than op it expects of one of '.', ';'. '?'. '}', or an operator.

How can I correctly write this macro? Or perhaps, another solution is best.

You can't, without changing the intent. Macros match literal tokens at compile time, not text in runtime variables like op. Maybe think of it this way: due to Rust being statically compiled, this expression has to call the same function (operator method) every time, whereas you wish it could be invoking different operations.

binary_op!(left, op, right)

If you're just trying to reduce repetition, perhaps this is closer to what you need.

2 Likes

I see now, thanks. The code you posted is perfect for my use case.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.