Course contentsShow
← Rust
Lesson 499 of 1,9105. Type System and TraitsFree lesson

Enum Variants as Data Carriers

Encode complex state using algebraic data types to ensure exhaustive handling.

In this lesson, you will learn how to leverage Rust’s algebraic data types to bundle unique data directly into enum variants, turning them into self-contained state containers.

In many languages, enums are simply named integers. In Rust, however, an enum variant is a powerful structure that can hold its own distinct data. This allows you to encode complex state transitions where each "phase" of your program’s lifecycle carries only the information relevant to that phase.

Consider a system representing a network connection:

enum ConnectionState {
    Disconnected,
    Connecting { server_addr: String },
    Connected { socket_id: u32, latency: u16 },
}

Instead of creating a giant struct with many Option fields (which often leads to invalid states like a Disconnected connection having a socket_id), you define exactly what data is required for each variant. When you transition from Connecting to Connected, you must provide the socket_id and latency. This architecture makes it impossible to exist in a "Connected" state without the necessary data, because the compiler enforces that you supply it during construction.

When you process this enum, you use pattern matching:

match state {
    ConnectionState::Disconnected => println!("Idle"),
    ConnectionState::Connecting { server_addr } => println!("To: {}", server_addr),
    ConnectionState::Connected { socket_id, .. } => println!("Active: {}", socket_id),
}

Because Rust’s type system is exhaustive, the compiler forces you to handle every variant. If you add a new variant, the code will fail to compile until you update all your match blocks to account for the new state. This provides a "compile-time guarantee" that your state management logic will never accidentally overlook a scenario, effectively eliminating an entire category of runtime "missing state" bugs. By tying data to specific variants, you transform your type system into a living document of your program's possible states.

Key Takeaway: Enum variants allow you to associate specific data with specific states, making invalid states unrepresentable and ensuring all logic handles your data exhaustively.