Start Coding

Rust Enums: Versatile Custom Types

Enums in Rust are a powerful feature that allows you to define a type by enumerating its possible variants. They are particularly useful for representing data that can be one of several possible types or states.

Defining an Enum

To define an enum in Rust, use the enum keyword followed by the name of the enum and its variants:


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

Each variant can be a unit-like struct, contain data, or even have different types of data:


enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}
    

Using Enums

To create an instance of an enum, you use the enum name followed by two colons and the variant name:


let direction = Direction::North;
let message = Message::Write(String::from("Hello, Rust!"));
    

Pattern Matching with Enums

Enums are often used with pattern matching, which allows you to handle different variants of an enum:


match direction {
    Direction::North => println!("Going north!"),
    Direction::South => println!("Going south!"),
    Direction::East => println!("Going east!"),
    Direction::West => println!("Going west!"),
}
    

The Option Enum

Rust's standard library includes a very useful enum called Option. It's used to express the possibility of absence:


enum Option<T> {
    Some(T),
    None,
}

let some_number = Some(5);
let absent_number: Option<i32> = None;
    

The Option enum is so common that it's included in the prelude; you don't need to bring it into scope explicitly. Its variants are also included: you can use Some and None directly without the Option:: prefix.

Key Benefits of Enums

  • Type safety: Enums ensure that a value is one of a predefined set of possibilities.
  • Expressiveness: They allow you to model domain concepts more accurately.
  • Pattern matching: Enums work seamlessly with Rust's powerful pattern matching feature.

Related Concepts

To fully leverage enums in Rust, you should also be familiar with:

Enums are a cornerstone of Rust's type system, providing a powerful way to express variants in your data structures. By mastering enums, you'll be able to write more expressive and safer Rust code.