Enums and pattern matching

Whenever you need to model something that can be of several different types, enums may be a good choice. The enum variants in Rust can be defined with or without data inside them, and the data fields can be either named or anonymous:

enum Direction {   N,   NE,   E,   SE,   S,   SW,   W,   NW } enum PlayerAction {   Move(direction: Direction, speed: u8),   Wait,   Attack(Direction)   } 

This defines two enum types: Direction and PlayerAction. For each of these enum types, this also defines a number of namespaced enum variants: Direction::N, Direction::NE, and so on for the Direction type, and PlayerAction::Move, PlayerAction::Wait, and PlayerAction::Attack for the PlayerAction type.

The most typical way of working with enums ...

Get Mastering Rust now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.