https://github.com/danaugrs/overload
Simplified operator overloading in Rust
https://github.com/danaugrs/overload
macros operator operator-overloading rust
Last synced: 9 months ago
JSON representation
Simplified operator overloading in Rust
- Host: GitHub
- URL: https://github.com/danaugrs/overload
- Owner: danaugrs
- License: mit
- Created: 2019-08-06T16:59:07.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-11-10T14:09:01.000Z (about 1 year ago)
- Last Synced: 2025-04-05T17:43:42.943Z (9 months ago)
- Topics: macros, operator, operator-overloading, rust
- Language: Rust
- Size: 30.3 KB
- Stars: 16
- Watchers: 2
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README

Provides a macro to simplify operator overloading. See the [documentation](https://docs.rs/overload/) for details and supported operators.
## Example
```rust
extern crate overload;
use overload::overload;
#[derive(PartialEq, Debug)]
struct Val {
v: i32
}
overload!((a: ?Val) + (b: ?Val) -> Val { Val { v: a.v + b.v } });
```
The macro call in the snippet above generates the following code:
```rust
impl std::ops::Add for Val {
type Output = Val;
fn add(self, b: Val) -> Self::Output {
let a = self;
Val { v: a.v + b.v }
}
}
impl std::ops::Add<&Val> for Val {
type Output = Val;
fn add(self, b: &Val) -> Self::Output {
let a = self;
Val { v: a.v + b.v }
}
}
impl std::ops::Add for &Val {
type Output = Val;
fn add(self, b: Val) -> Self::Output {
let a = self;
Val { v: a.v + b.v }
}
}
impl std::ops::Add<&Val> for &Val {
type Output = Val;
fn add(self, b: &Val) -> Self::Output {
let a = self;
Val { v: a.v + b.v }
}
}
```
We are now able to add `Val`s and `&Val`s in any combination:
```rust
assert_eq!(Val{v:3} + Val{v:5}, Val{v:8});
assert_eq!(Val{v:3} + &Val{v:5}, Val{v:8});
assert_eq!(&Val{v:3} + Val{v:5}, Val{v:8});
assert_eq!(&Val{v:3} + &Val{v:5}, Val{v:8});
```