2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#171 in Rust patterns

Download history 1193939/week @ 2024-07-23 1181800/week @ 2024-07-30 1207386/week @ 2024-08-06 1213612/week @ 2024-08-13 1282474/week @ 2024-08-20 1198891/week @ 2024-08-27 1323726/week @ 2024-09-03 1257463/week @ 2024-09-10 1208853/week @ 2024-09-17 1319892/week @ 2024-09-24 1327930/week @ 2024-10-01 1338603/week @ 2024-10-08 1415865/week @ 2024-10-15 1441684/week @ 2024-10-22 1370058/week @ 2024-10-29 1386986/week @ 2024-11-05

5,832,818 downloads per month
Used in 499 crates (6 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