Back to the where version
The where
version of the code is more complex than the non-where version.
Note
The source for this version can be found in 09/generic_trait_where
.
Let's examine the code:
extern crate num; use std::ops::{Add, Mul}; use num::FromPrimitive;
We have seen std::ops::Mul
before in the generic multiplication example. If we need to include multiple items from std::ops
(or indeed any library), they are held in curly braces; {}
. Here, we include Add
and Mul
.
Up until this point, we have not seen the extern crate
directive. For now, it is enough to know that this will include an external library. Crates are covered in Chapter 9, Generics and Traits.
Finally, we use FromPrimitive
from the num
library.
Our struct
and trait
are the same as before. The implementation, though, is different:
impl<T> Calculate<T> for Shape<T> where T: Copy + FromPrimitive + Add<Output = T> + Mul<Output = T> { fn calc(&self) -> T { let two = T::from_u8(2...