2

Can I define my own operator symbol in Rust? If so, how?

For example, a + b is equivalent to a.add(b). Can I define a symbol like ~ so that a ~ b is equivalent to a.myop(b) for some method myop? (I'm assuming ~ has no other meaning in Rust which I think is true.)

Of course I would expect this operator to be implemented the same way operators in std::ops are, so an implementation would look like:

impl<T> MyOp<T> for MyStruct {
    type Output = x;
    fn myop(self, other: T) -> x {
        ...
    }
}

Also, if this is possible what symbols are allowed?

wyoumans
  • 350
  • 1
  • 3
  • 10
  • 3
    I don't believe this is possible, but you could create a macro that expands `a ~ b` to `a.myop(b)`. – Lauren Yim Aug 07 '21 at 03:49
  • @kmdreko I didn't see that, thanks! To be pedantic though the answer there doesn't mention that there is no mechanism to create new operators which I think is important (not to mention the link is outdated). – wyoumans Aug 07 '21 at 03:59
  • 1
    @wyoumans on the contrary, the linked question is *"Can we create custom Rust operators?"* and the linked answer is *"No"*. But thanks for pointing that out, I've updated the link. – kmdreko Aug 07 '21 at 04:07
  • @cherryblossom thanks for the comment. What would this macro look like? I'm confused about how this could be done. – wyoumans Aug 07 '21 at 04:09
  • @kmdreko the linked answer does say "No" but doesn't provide any source. It only lists operators which can be overloaded which is irrelevant since the question is "Can we create custom Rust operators?" – wyoumans Aug 07 '21 at 04:15

1 Answers1

4

No.

Only operators backed by traits can be overloaded. For example, the addition operator (+) can be overloaded through the Add trait, but since the assignment operator (=) has no backing trait, there is no way of overloading its semantics. Additionally, this module does not provide any mechanism to create new operators.

https://doc.rust-lang.org/std/ops/index.html

Strikegently
  • 2,251
  • 20
  • 23