Basic enumerations

In Rust, an enumeration is a data type representing one of a fixed set of values. For example, we could define an enumeration of the commonly recognized seven colors of the rainbow, as shown here:

pub enum Color {
Red,
Orange,
Yellow,
Green,
Blue,
Indigo,
Violet,
}

Once we define this enumeration, we can use Color as a data type and Color::Red or the like as data values of that type:

let color: Color = Color::Green;

An enumeration is created with the enum keyword. Notice that, like a structure, an enumeration needs the pub keyword if we want it to be directly accessible outside the current module. Between the { and }we have the list of possible values for the data type, listed by name and separated by commas.

Rust is somewhat opinionated about capitalization, so it will warn us if any of the enumeration values start with a lowercase letter, though that is not actually an error.

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

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