Enums

Learn how to work with Enums, your first introduction to defining custom types with distinct variants.

Enums, short for “enumerations,” are a powerful feature in Rust that allows you to define a type by enumerating its possible values. They are particularly useful for enhancing type safety and leveraging Rust’s pattern-matching capabilities to write concise and expressive code. An enum in Rust is defined using the enum keyword, allowing us to list all possible variants of a type. This is especially useful when dealing with a value that can only be one of several distinct options. Rust’s enums are more powerful than enums in many other languages because each variant can optionally carry associated data of different types.

Syntax

Enums are defined using the enum keyword followed by the name of the enum. Inside the curly brackets, we provide the different enum variants. The syntax is shown below:

The name of the enum and the variants must follow a capital camel case convention.

Get hands-on with 1400+ tech skills courses.