Rust Data Structures
Estimated reading: 3 minutes 32 views

🦀 Rust – Enums: Model Data Variants with Type Safety

🧲 Introduction – Why Learn Enums in Rust?

Enums in Rust are more than just “choices”—they’re powerful tools for representing data variants, state transitions, and pattern matching. Whether you’re building a CLI parser or handling app states, enums paired with match offer type-safe branching with minimal runtime cost.

🎯 In this guide, you’ll learn:

  • How to define and use enums in Rust
  • How to attach data to enum variants
  • How match and if let handle enum control flow
  • Code examples with outputs and detailed explanations

✅ Defining a Basic Enum

🔹 Code Example:

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

fn main() {
    let go = Direction::North;
    match go {
        Direction::North => println!("Heading North"),
        Direction::South => println!("Going South"),
        Direction::East  => println!("Turning East"),
        Direction::West  => println!("Moving West"),
    }
}

📤 Output:

Heading North

📦 Enums with Attached Data (Variant Payloads)

🔹 Code Example:

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

fn main() {
    let msg = Message::Move { x: 10, y: 20 };

    match msg {
        Message::Quit => println!("Quit command received"),
        Message::Move { x, y } => println!("Move to ({}, {})", x, y),
        Message::Write(text) => println!("Message: {}", text),
    }
}

📤 Output:

Move to (10, 20)

🔄 Enums with Tuple-like Variants

🔹 Code Example:

enum Color {
    RGB(u8, u8, u8),
    CMYK(u8, u8, u8, u8),
}

fn main() {
    let shade = Color::RGB(255, 0, 0);

    match shade {
        Color::RGB(r, g, b) => println!("RGB({}, {}, {})", r, g, b),
        Color::CMYK(c, m, y, k) => println!("CMYK({}, {}, {}, {})", c, m, y, k),
    }
}

📤 Output:

RGB(255, 0, 0)

🧪 Using if let for Simpler Matching

🔹 Code Example:

enum Status {
    Success,
    Error(String),
}

fn main() {
    let result = Status::Error(String::from("File not found"));

    if let Status::Error(msg) = result {
        println!("Error: {}", msg);
    }
}

📤 Output:

Error: File not found

if let is concise for matching a single variant.


🎯 Enum with Methods via impl

🔹 Code Example:

enum Operation {
    Add,
    Multiply,
}

impl Operation {
    fn run(&self, x: i32, y: i32) -> i32 {
        match self {
            Operation::Add => x + y,
            Operation::Multiply => x * y,
        }
    }
}

fn main() {
    let op = Operation::Add;
    println!("Result: {}", op.run(3, 4));
}

📤 Output:

Result: 7

⚠️ Enums and Ownership

Enums behave like structs—they can own data, and their fields follow Rust’s ownership and borrowing rules.

🔹 Code Example:

enum Packet {
    Data(String),
}

fn main() {
    let data = String::from("Payload");
    let pkt = Packet::Data(data);
    // println!("{}", data); // ❌ Error: value moved
}

🔄 Enums vs Structs vs Tuples

FeatureEnumsStructsTuples
Type groupingOne of many variantsAll fields always presentFixed-size values by position
Can hold dataYes (per variant)YesYes
Match compatible✅ Pattern matching requiredPartial support via destructuring

📌 Summary – Recap & Next Steps

Enums in Rust offer a robust and expressive way to model choices and data variants, especially with match expressions. They’re ideal for state machines, parsers, and result/error types (Option, Result, etc.).

🔍 Key Takeaways:

  • Enums group multiple named variants, optionally with data
  • Use match or if let to destructure and respond to variants
  • You can implement methods on enums with impl
  • Perfect for modeling state transitions and tagged unions

⚙️ Up next: Explore Rust – Option & Result Enums, the most widely used enums in real-world Rust apps.


❓FAQs


Can an enum variant hold data in Rust?
✅ Yes! You can attach data to specific variants using struct-like or tuple-like syntax.


What’s the difference between match and if let?
match handles all variants explicitly; if let is shorter but only handles one pattern.


Can enums have methods in Rust?
✅ Yes. Use an impl block just like structs.


What happens if I forget to handle a variant in match?
❌ Rust will raise a compile-time error unless you use a wildcard (_ =>) arm.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust – Enums

Or Copy Link

CONTENTS
Scroll to Top