2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#372 in Rust patterns

Download history 1151423/week @ 2025-12-09 998261/week @ 2025-12-16 501683/week @ 2025-12-23 531291/week @ 2025-12-30 966028/week @ 2026-01-06 1033201/week @ 2026-01-13 1117989/week @ 2026-01-20 1163227/week @ 2026-01-27 1295173/week @ 2026-02-03 1225745/week @ 2026-02-10 1042037/week @ 2026-02-17 1051010/week @ 2026-02-24 1260657/week @ 2026-03-03 1167393/week @ 2026-03-10 999269/week @ 2026-03-17 1061538/week @ 2026-03-24

4,645,177 downloads per month
Used in 128 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