2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#271 in Rust patterns

Download history 817004/week @ 2024-01-05 863114/week @ 2024-01-12 901956/week @ 2024-01-19 923855/week @ 2024-01-26 958653/week @ 2024-02-02 970068/week @ 2024-02-09 933959/week @ 2024-02-16 1003789/week @ 2024-02-23 1016168/week @ 2024-03-01 976927/week @ 2024-03-08 981544/week @ 2024-03-15 985479/week @ 2024-03-22 958872/week @ 2024-03-29 982894/week @ 2024-04-05 1021583/week @ 2024-04-12 853099/week @ 2024-04-19

3,997,027 downloads per month
Used in 358 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