#macro #op #operator-overloading

overload

Provides a macro to simplify operator overloading

2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#297 in Rust patterns

Download history 630470/week @ 2023-11-21 742264/week @ 2023-11-28 748060/week @ 2023-12-05 808076/week @ 2023-12-12 635551/week @ 2023-12-19 405321/week @ 2023-12-26 756688/week @ 2024-01-02 832662/week @ 2024-01-09 897780/week @ 2024-01-16 894946/week @ 2024-01-23 972938/week @ 2024-01-30 944817/week @ 2024-02-06 946073/week @ 2024-02-13 983449/week @ 2024-02-20 1002640/week @ 2024-02-27 825019/week @ 2024-03-05

3,919,788 downloads per month
Used in 336 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