[−][src]Macro auto_ops::impl_op_commutative
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 *
.
ⓘThis example deliberately fails to compile
impl_op_commutative!(op |a: LHS, b: RHS| -> OUT {...}); // where LHS != RHS
gets expanded to
ⓘThis example deliberately fails to compile
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
use auto_ops::impl_op_commutative; 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 }