2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#178 in Rust patterns

Download history 1271447/week @ 2024-08-23 1209367/week @ 2024-08-30 1302884/week @ 2024-09-06 1189050/week @ 2024-09-13 1335025/week @ 2024-09-20 1288459/week @ 2024-09-27 1378022/week @ 2024-10-04 1342062/week @ 2024-10-11 1439782/week @ 2024-10-18 1420132/week @ 2024-10-25 1358873/week @ 2024-11-01 1402783/week @ 2024-11-08 1445836/week @ 2024-11-15 1314587/week @ 2024-11-22 1348686/week @ 2024-11-29 1392727/week @ 2024-12-06

5,772,362 downloads per month
Used in 496 crates (7 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