O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required