Checking the value type and extracting parameter values

When the program runs, it can take different actions depending on the specific enumeration type it's looking at, and it has access to the data values that were stored as parameters. We've already seen the best tool for doing that, match:

    for step in directions.iter() {
match step {
Drive::Forward(blocks) => {
println!("Drive forward {} blocks", blocks);
},
Drive::Turn{slight, right} => {
println!("Turn {}{}",
if *slight {
"slightly "
}
else {
""
},
if *right {
"right"
}
else {
"left"
}
);
},
Drive::Stop => {
println!("You have reached your destination");
}
};
};

Here, we have a for loop that processes each item in our array of directions, one at a time, starting with the first one. Step by step, here's what is going on:

  1. We asked directions to provide us with an iterator, which it's happy to do. The iterator will give us a borrow of each value contained in the array, one at a time.
  2. The for loop requests a value from the iterator, and assigns the returned borrow to a variable called step.
  1. The match expression uses the step variable to provide the value that it will match against. Because that variable changes each time the loop goes through, the match expression compares against a different value each time:
    • If the step variable contains (a borrow of) Drive::Forward, its parameter is assigned to the variable named blocks. Because step is a borrow, the value in blocks is a borrow as well, but, in this instance that doesn't make a significant difference. We pass it on to println!, which calls a function on it to turn it into a text string, which in turn, dereferences it automatically.
    • If the step variable contains (a borrow of) Drive::Turn, borrows of its parameters are assigned to the slight and right names, and we can use the shorthand notation we've seen before for that because slight and right are the names of the variables in both the source and the destination. Then comes a print command, but we're using if expressions to decide exactly what to print. Notice that we have explicitly dereferenced the slight and right values; they are borrows and, unlike when we call functions, if expressions don't automatically dereference for us, so we need to do it ourselves.
    • If the step variable contains (a borrow of) Drive::Stop, there are no parameters to deal with and we just print out a message.
  2. If there are any values left in the iterator, got back to step 2.

Pretty cool. We've got some code here that does something kind of real. That's when the fun really starts!

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

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