rustc/vendor/overload-0.1.1
2024-06-24 14:48:22 +02:00
..
src New upstream version 1.79.0+dfsg1 2024-06-24 14:48:22 +02:00
tests New upstream version 1.79.0+dfsg1 2024-06-24 14:48:22 +02:00
.cargo-checksum.json New upstream version 1.79.0+dfsg1 2024-06-24 14:48:22 +02:00
Cargo.toml New upstream version 1.79.0+dfsg1 2024-06-24 14:48:22 +02:00
LICENSE New upstream version 1.79.0+dfsg1 2024-06-24 14:48:22 +02:00
logo.png New upstream version 1.79.0+dfsg1 2024-06-24 14:48:22 +02:00
README.md New upstream version 1.79.0+dfsg1 2024-06-24 14:48:22 +02:00

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});