Implementing our PrintableDirection trait

Traits don't exist independently; they are something that data types have. So, the first thing we need to do is create data types to represent the various kinds of driving directions:

pub struct Forward {
pub blocks: u8,
}

pub struct Turn {
pub slight: bool,
pub right: bool,
}

pub struct Stop {}
We're just using basic structures here, but traits can be implemented for any data type.

These structures contain the same information that we included in the enumeration parameters before. The Stop structure is interesting, because it's empty. It stores no information at all. Its only purpose is to be a data type.

Now, we have a trait and we have data types, but so far they are not related in any way. Let's implement our trait for each of these types:

impl PrintableDirection for Forward {
fn forward(&self) {
println!("Go forward {} blocks", self.blocks);
}

fn reverse(&self) {
println!("Go forward {} blocks", self.blocks);
}
}

impl PrintableDirection for Turn {
fn forward(&self) {
println!("Turn {}{}",
if self.slight {"slightly "} else {""},
if self.right {"right"} else {"left"});
}

fn reverse(&self) {
println!("Turn {}{}",
if self.slight {"slightly "} else {""},
if self.right {"left"} else {"right"});
}
}

impl PrintableDirection for Stop {
fn forward(&self) {
println!("You have reached your destination");
}

fn reverse(&self) {
println!("Turn 180 degrees");
}
}

These implementation blocks look similar to the ones we've seen before, but this time instead of just saying impl and the type name, they say to implement the trait for the type name. Then, inside of it, we place the specific versions of the trait's functions that apply to that data type.

The Forward, Turn, and Stop data types now each have the PrintableDirection trait, which means that each of them knows how to display the information it contains as a driving instruction.

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

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