Back to the where version

The where version of the code is more complex than the non-where version.

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).expect("Unable to create a value of 2");
self.line_one * two + self.line_two * two
}
}

There are two important lines in this code: where T:Copy + FromPrimitive + Add<Output = T> + Mul<Output = T> and let two = T::from_u8(2).expect("Unable to create a value of 2");.

Here, we are saying that we want to copy the type, we'll be using FromPrimitive to cast a primitive to T, and both the Add and Mul outputs will be of type T. Rust concatenates the parameters that a where uses using +.

The let two line creates a variable that takes an unsigned 8-bit value and casts that to T. If it fails, the error is thrown.

We have to use Add<Output = T> to ensure we can add the types together.

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

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