enum

Enums in rust are quite similar to other languages, in that it is a constrained set of variants of possible values for a given type. They look like this:

enum Direction {
    North,
    South,
    East,
    West,
}

println!("{}", Direction::North);

What’s interesting, though, is that you can also impl methods on enums, just like a struct. Crazy!

impl Direction {
    fn is_north(&self) -> bool {
        matches!(self, Direction::North)
    }

    fn print_direction(&self) {
        match self {
            Direction::North => println!("Heading North"),
            Direction::South => println!("Heading South"),
            Direction::East  => println!("Heading East"),
            Direction::West  => println!("Heading West"),
        }
    }
}
end of storey Last modified: