Enums
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 file:
use PlanetaryMonster::MarsMonster;
Then the type can be shortened, like this:
let martian = MarsMonster("Chela", 42);
The enums are really nice to bring readability in your code, and they are used a lot in Rust. To apply them usefully...