2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#261 in Rust patterns

Download history 992571/week @ 2024-03-06 973833/week @ 2024-03-13 988188/week @ 2024-03-20 937091/week @ 2024-03-27 996553/week @ 2024-04-03 1019200/week @ 2024-04-10 1019391/week @ 2024-04-17 1026281/week @ 2024-04-24 982226/week @ 2024-05-01 993055/week @ 2024-05-08 1036949/week @ 2024-05-15 1024422/week @ 2024-05-22 1108464/week @ 2024-05-29 1118717/week @ 2024-06-05 1159442/week @ 2024-06-12 886446/week @ 2024-06-19

4,464,718 downloads per month
Used in 373 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