#operator #overloading #macro #op

overload

Provides a macro to simplify operator overloading

2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#549 in Rust patterns

Download history 1206/week @ 2022-06-05 1991/week @ 2022-06-12 1716/week @ 2022-06-19 1419/week @ 2022-06-26 1420/week @ 2022-07-03 1688/week @ 2022-07-10 1281/week @ 2022-07-17 2456/week @ 2022-07-24 1972/week @ 2022-07-31 2119/week @ 2022-08-07 1185/week @ 2022-08-14 1001/week @ 2022-08-21 1552/week @ 2022-08-28 2917/week @ 2022-09-04 3511/week @ 2022-09-11 5367/week @ 2022-09-18

13,454 downloads per month
Used in 62 crates (5 directly)

MIT license

25KB
112 lines

Provides a macro to simplify operator overloading. See the documentation for details and supported operators.

Example

extern crate overload;
use overload::overload;
use std::ops; // <- don't forget this or you'll get nasty errors

#[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:

impl 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 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 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 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 Vals and &Vals in any combination:

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});

No runtime deps