-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
There's some controversy over custom operators and them being overused in cases that don't really make sense and how they can be more confusing than helpful. I personally love them and think that they, when used wisely, can really make certain APIs much more appealing.
Rust allows you to overload a few basic operators using traits defined in the standard library. That's great but you're very limited to what you can actually do with them.
I'd like to point you to Swift here. They have solved this problem rather nicely.
You can implement operator functions and define some properties on them, like:
- Precedence
- Left or right asociativity
- Prefix, infix, or postfix
Here's how Rust could look defining a custom null coalescing operator:
op ?? {
assoc: left,
prec: 100,
}
infx fn ??<T>(l: Option<T>, r: T) -> T {
match l {
Some(s) => s,
None => r,
}
}
I haven't given too much thought to the example above, it's probably suboptimal and doesn't play too well with the existing syntax. So it's just an example.
Basically, I'm interested in hearing what other people would think of more generic operator overloading functionality in Rust.
As I said before:
Btw Rust is super awesome :D 🤘
Fantastic work guys