AddAssign, MulAssign, SubAssign, and DivAssign

These traits enable the +=, *=, -=, and /= operators for the types that implement them.

They are similar to the Add, Sub, Mul, and Div traits, with the difference that their implementation functions take &mut self instead of plain self. Instead of consuming their left-side input, they have the ability to change its contained value.

All of these traits follow the same pattern, so here's an example implementation of AddAssign:

pub enum AddExample {
One,
Two,
Three,
Many,
}

impl AddAssign for AddExample {
fn add_assign(&mut self, other: AddExample) {
*self = match (&self, other) {
(AddExample::One, AddExample::One) => AddExample::Two,
(AddExample::One, AddExample::Two) => AddExample::Three,
(AddExample::Two, AddExample::One) => AddExample::Three,
_ => AddExample::Many,
};
}
}

Apart from the differences based on assigning the new value to &mut self, this is much like the implementation of the add function for the Add trait, which isn't very surprising.

In particular, while it doesn't consume its self, it does still consume the value on the right-hand side of the operand, assuming that value doesn't have the Copy trait.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.77.63