impl_ops

Macros for easy operator overloading

2 releases

Uses old Rust 2015

0.1.1 Jul 10, 2017
0.1.0 Jul 6, 2017

#947 in Rust patterns

Download history 2407/week @ 2024-06-18 3086/week @ 2024-06-25 3435/week @ 2024-07-02 3257/week @ 2024-07-09 4962/week @ 2024-07-16 3588/week @ 2024-07-23 2870/week @ 2024-07-30 3391/week @ 2024-08-06 2280/week @ 2024-08-13 2840/week @ 2024-08-20 2675/week @ 2024-08-27 1870/week @ 2024-09-03 2261/week @ 2024-09-10 1811/week @ 2024-09-17 2672/week @ 2024-09-24 2733/week @ 2024-10-01

9,884 downloads per month
Used in 16 crates (13 directly)

MIT license

27KB
250 lines

impl_ops Build Status Latest Version

NOTICE: This crate is stable, but won't be receiving new features. For a more up-to-date version of this crate see auto_ops.

Macros for easy operator overloading.

Documentation

This library makes writing multiple impl std::ops::<op> blocks much faster, especially when you want operators defined for both owned and borrowed variants of the inputs.

To use, include #[macro_use] extern crate impl_ops; in your crate and use std::ops; in your module. Remember that you can only overload operators between one or more types defined in the current crate.

Examples

#[macro_use] extern crate impl_ops;
use std::ops;

#[derive(Clone, Debug, PartialEq)]
struct DonkeyKong {
    pub bananas: i32,
}
impl DonkeyKong {
    pub fn new(bananas: i32) -> DonkeyKong {
        DonkeyKong { bananas: bananas }
    }
}

impl_op_ex!(+ |a: &DonkeyKong, b: &DonkeyKong| -> DonkeyKong { DonkeyKong::new(a.bananas + b.bananas) });
impl_op_ex!(+= |a: &mut DonkeyKong, b: &DonkeyKong| { a.bananas += b.bananas });

fn main() {
    assert_eq!(DonkeyKong::new(5), DonkeyKong::new(4) + DonkeyKong::new(1));
    assert_eq!(DonkeyKong::new(5), DonkeyKong::new(4) + &DonkeyKong::new(1));
    assert_eq!(DonkeyKong::new(5), &DonkeyKong::new(4) + DonkeyKong::new(1));
    assert_eq!(DonkeyKong::new(5), &DonkeyKong::new(4) + &DonkeyKong::new(1));

    let mut dk = DonkeyKong::new(4);
    dk += DonkeyKong::new(1);
    dk += &DonkeyKong::new(1);
    assert_eq!(DonkeyKong::new(6), dk);
}

Roadmap

This crate is stable but no longer receiving feature updates. Please see auto_ops for a more up-to-date fork of this crate.

No runtime deps