November 2017
Intermediate to advanced
264 pages
5h 45m
English
If something can only be one of a limited number of named values, then we define it as an enum. For example, if our game needs the compass directions, we could define:
// from Chapter 4/code/enums.rs
enum Compass {
North, South, East, West
}
And use it like this in function main() or any another function:
let direction = Compass::West;
The enum's values can also be other types or structs, like in this example, where we define a type species:
type species = &'static str;
enum PlanetaryMonster {
VenusMonster(species, i32),
MarsMonster(species, i32)
}
let martian = PlanetaryMonster::MarsMonster("Chela", 42);
The enums are sometimes called union types or algebraic data types in other languages.
If we make a use at the start of the code ...
Read now
Unlock full access