☼
⌃
☰

Enums in Rust

Table of Contents

Enums in Rust

In Rust, enums (enumerations) are custom data types that allow you to define a type by enumerating its possible values, known as "variants." Unlike structs, which represent a "product type" (an instance has all its defined fields), enums represent a "sum type" (an instance is one of its defined variants). This makes enums incredibly powerful for representing data that can take one of several different forms.

Core Concepts

  • Variants: Each possible value an enum can take is called a variant.
  • Associated Data: Crucially, each enum variant can optionally have data associated with it. This data can be:
    • Unit-like: No data (e.g., Message::Quit).
    • Tuple-like: Data without names (e.g., Message::Move(x, y)).
    • Struct-like: Data with named fields (e.g., Message::Write { text: String }).
  • Pattern Matching (match expression): The primary way to work with enums is through the match expression. This allows you to execute different code based on which variant an enum value holds and to extract any associated data.
  • Exhaustiveness: Rust's match expression is exhaustive, meaning you must handle every possible variant of an enum. This provides strong compile-time guarantees, preventing bugs where you forget to handle a case.
  • Single Type: Despite having different variants with potentially different associated data, an enum itself is a single type.

Defining an Enum

RUST
// Example: A Message enum representing different kinds of messages
enum Message {
    Quit, // Unit-like variant (no data)
    Move { x: i32, y: i32 }, // Struct-like variant (named fields)
    Write(String), // Tuple-like variant (unnamed data)
    ChangeColor(i32, i32, i32), // Another tuple-like variant
}

Instantiating Enum Variants

You create instances of enum variants using the enum name followed by:: and the variant name, along with any associated data.

RUST
let m1 = Message::Quit;
let m2 = Message::Move { x: 10, y: 20 };
let m3 = Message::Write(String::from("hello"));
let m4 = Message::ChangeColor(255, 0, 0);

Using Enums with Match

The match expression is the most common way to destructure enum values and execute code based on their variant.

RUST
fn process_message(msg: Message) {
    match msg {
        Message::Quit => {
            println!("The Quit variant has no data.");
        }
        Message::Move { x, y } => { // Destructure named fields
            println!("Move to x: {}, y: {}", x, y);
        }
        Message::Write(text) => { // Destructure tuple data
            println!("Text message: {}", text);
        }
        Message::ChangeColor(r, g, b) => { // Destructure tuple data
            println!("Change color to R:{}, G:{}, B:{}", r, g, b);
        }
    }
}

// Example usage:
process_message(Message::Move { x: 5, y: 8 });
process_message(Message::Write(String::from("Hello Rust!")));

The Option Enum

One of the most important and frequently used enums in Rust is Option, which handles the presence or absence of a value. It's how Rust explicitly manages nullability, preventing "null pointer dereference" errors common in other languages.

RUST
enum Option<T> {
    None, // Represents no value
    Some(T), // Represents a value of type T
}

// Example usage:
let some_number = Some(5); // An Option holding an integer
let some_string = Some("a string"); // An Option holding a string slice
let absent_number: Option<i32> = None; // An Option holding no value

// Using match with Option:
match some_number {
    Some(number) => println!("There is a number: {}", number),
    None => println!("There is no number."),
}

The Result<T, E> Enum

Another crucial enum is Result<T, E>, used for error handling. It represents either a successful outcome (Ok(T)) or a failure (Err(E)).

RUST
enum Result<T, E> {
    Ok(T),    // Represents a successful value of type T
    Err(E),   // Represents an error value of type E
}

Methods on Enums

Like Structs in Rust, enums can have methods defined in an impl block.

RUST
impl Message {

    fn call(&self) {

        // Method implementation depends on the variant

        match self {

            Message::Write(text) => println!("Calling with text: {}", text),

            _ => println!("Calling with other message type."), // Wildcard for other variants

        }

    }

}

let msg_write = Message::Write(String::from("Hello from method!"));

msg_write.call();

Key Advantages of Enums

  • Type Safety for Diverse Data: Allows a variable to strictly be one of a defined set of values, each potentially carrying different associated data.
  • Eliminates Null Pointers (Option): Forces developers to explicitly handle the possibility of a value being absent, making code more robust.
  • Robust Error Handling (Result<T, E>): Provides a structured and type-safe way to manage recoverable errors, encouraging explicit error handling.
  • Compile-Time Guarantees: The match expression's exhaustiveness check ensures all possible cases are handled, preventing runtime bugs.
  • Clearer Code: Makes code more readable and expressive by clearly defining all possible states or types of data.
  • Algebraic Data Types: Rust enums are a form of Algebraic Data Types (ADTs), a powerful concept from Functional Programming that enables strong type guarantees and expressive pattern matching.