Macro impl_ops::impl_op_commutative
source · [−]macro_rules! impl_op_commutative {
($op:tt |$lhs_i:ident : &$lhs:path, $rhs_i:ident : &$rhs:path| -> $out:path $body:block) => { ... };
($op:tt |$lhs_i:ident : &$lhs:path, $rhs_i:ident : $rhs:path| -> $out:path $body:block) => { ... };
($op:tt |$lhs_i:ident : $lhs:path, $rhs_i:ident : &$rhs:path| -> $out:path $body:block) => { ... };
($op:tt |$lhs_i:ident : $lhs:path, $rhs_i:ident : $rhs:path| -> $out:path $body:block) => { ... };
}
Expand description
Overloads a binary operator commutatively using the given closure as its body.
Used with the same syntax as impl_op!
(see the module level documentation for more information).
Can only be used with binary operators, and the operation must be between two different types.
An operator is commutative if A +
and *
.
ⓘ
impl_op_commutative!(op |a: LHS, b: RHS| -> OUT {...});
// where LHS != RHS
gets expanded to
ⓘ
impl_op!(op |a: LHS, b: RHS| -> OUT {...});
impl_op!(op |a: RHS, b: LHS| -> OUT {...});
Make sure that LHS != RHS, and that the operator you are trying to overload is a commutative one.
See the examples for what happens when you try impl_op_commutative!
on the -
operator (which isn’t usually commutative).
Examples
#[macro_use] extern crate impl_ops;
use std::ops;
impl_op_commutative!(+ |a: DonkeyKong, b: i32| -> i32 { a.bananas + b });
// Don't do this unless you know what you are doing:
impl_op_commutative!(- |a: DonkeyKong, b: i32| -> i32 { a.bananas - b });
fn main() {
let total_bananas = DonkeyKong::new(5) + 1;
assert_eq!(6, total_bananas);
let total_bananas = 1 + DonkeyKong::new(5);
assert_eq!(6, total_bananas);
let total_bananas = DonkeyKong::new(5) - 1;
assert_eq!(4, total_bananas);
let total_bananas = 1 - DonkeyKong::new(5);
assert_eq!(4, total_bananas);
// notice that in this case (5 - 1 == 4) and (1 - 5 == 1): that is the definition of a
// commutative operator, but probably not what you want for the '-' operator
}