#operator #overloading #macro #op

overload

Provides a macro to simplify operator overloading

2 releases

0.1.1 Aug 10, 2019
0.1.0 Aug 6, 2019

#1 in #operator

Download history 764941/week @ 2023-10-20 805147/week @ 2023-10-27 804001/week @ 2023-11-03 834746/week @ 2023-11-10 712659/week @ 2023-11-17 684618/week @ 2023-11-24 752472/week @ 2023-12-01 789463/week @ 2023-12-08 766998/week @ 2023-12-15 429976/week @ 2023-12-22 596918/week @ 2023-12-29 817040/week @ 2024-01-05 863148/week @ 2024-01-12 901994/week @ 2024-01-19 923891/week @ 2024-01-26 802179/week @ 2024-02-02

3,642,388 downloads per month
Used in 327 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