​Add, Mul, Sub, and Div

The Add, Mul, Sub, and Div traits represent the ability to add, multiply, subtract, or divide two values. These traits are used by the compiler to implement the +, *, -, and / operators.

Notice that if the values of self and other do not have the Copy trait, they are moved into the implementation function and consumed.

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

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

impl Add for AddExample {
type Output = AddExample;

fn add(self, other: AddExample) -> AddExample {
match (self, other) {
(AddExample::One, AddExample::One) => AddExample::Two,
(AddExample::One, AddExample::Two) => AddExample::Three,
(AddExample::Two, AddExample::One) => AddExample::Three,
_ => AddExample::Many,
}
}
}

Mul, Sub, and Div follow the same pattern.

What we've defined here is a very primitive form of counting, that considers any number greater than 3 to be "many".

Inside the impl block, we have type Output = AddExample;. That's a bit of new syntax we haven't seen before. What we're doing is setting the Output associated type for this implementation, which is fed back into the trait definition to be used in declaring the signature of the add function. After all, we're returning an AddExample here, and there was no such type when the trait was originally defined. That's not a problem, though, because the trait says that the add function returns a data value of type Output, and we've just told it that Output is an alias for AddExample.

We can also implement adding data of two different types together, by implementing Add<OtherType> for OneType to represent the ability to have a OneType value on the left side of the + and an OtherType value on the right, similarly to the way we were able to create comparisons between two different types earlier in the chapter. The same trick works for Mul, Sub, and Div as well.

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

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