2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#222 in Rust patterns

Download history 2581463/week @ 2025-08-04 2601981/week @ 2025-08-11 2567049/week @ 2025-08-18 2430333/week @ 2025-08-25 1777214/week @ 2025-09-01 1657657/week @ 2025-09-08 1601396/week @ 2025-09-15 1440454/week @ 2025-09-22 1417324/week @ 2025-09-29 1394219/week @ 2025-10-06 1254100/week @ 2025-10-13 1296254/week @ 2025-10-20 1309231/week @ 2025-10-27 1413318/week @ 2025-11-03 1279076/week @ 2025-11-10 1306363/week @ 2025-11-17

5,394,866 downloads per month
Used in 125 crates (8 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