Parameterized enumerations

Okay, so what do enumerations have to do with representing different kinds of data in one variable? Well, there's one more feature that enumeration values can have that changes everything: parameters.

Imagine we wanted to create a representation of a sequence of driving directions, such as turn right, forward three blocks, or stop. This example is simple enough that we could probably get by with a simple enumeration, but even this will be easier with parameters:

pub enum Drive {
Forward(u8),
Turn{slight: bool, right: bool},
Stop,
}

What we have here is an enumeration with parameterized values. The Forward value has a u8 parameter (unsigned 8 bit integer) , while the Turn value has two bool parameters with names. Stop doesn't need any parameters.

Essentially, the Forward value carries a 1-tuple along with it, while the Turn value carries along a structure with two members. That's why parentheses are used around the Forward parameter and braces are used around the Turn parameters. Whether we want the parameters to be tuple-like or structure-like is our decision to make. Either way, we can have as many or as few parameters as we need.

Now, we can create a variable of the Drive type, and it might contain a ForwardTurn, or Stop parameter. If it's a Forward parameter, that means the variable also contains a u8 number telling us how far to drive. If it's a Turn parameter, that means the variable also contains a pair of Boolean values that tell us whether to turn right or left, and whether or not the turn is slight. In other words, the variable might contain any one of several different kinds of information.

If you're familiar with C++, or a similar language, keep in mind that Rust enumerations are not very much like C++ enumerations. A Rust enumeration with parameterized values is more like a C++ union, except it's type checked and safe.

Better still, we can create an array of driving instructions, to represent a complete journey:

let directions = [
Drive::Forward(3),
Drive::Turn{slight: false, right: true},
Drive::Forward(1),
Drive::Stop,
];

This array of Drive values represents driving forward three blocks, turning right, driving forward one more block, and stopping.

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

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