2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#275 in Rust patterns

Download history 734161/week @ 2023-12-16 400166/week @ 2023-12-23 654493/week @ 2023-12-30 834830/week @ 2024-01-06 871016/week @ 2024-01-13 883452/week @ 2024-01-20 948678/week @ 2024-01-27 959157/week @ 2024-02-03 963633/week @ 2024-02-10 946258/week @ 2024-02-17 1002887/week @ 2024-02-24 1005741/week @ 2024-03-02 982237/week @ 2024-03-09 980239/week @ 2024-03-16 963658/week @ 2024-03-23 826629/week @ 2024-03-30

3,907,726 downloads per month
Used in 350 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