Rust Enums Can Hold Data, Not Just Constants

Day 9/90: Rust Enums Just Broke My Brain (In a Good Way) 🎲 Thought I knew what enums were from Python. I was wrong. Python enum: class Status(Enum):   PENDING = 1   APPROVED = 2   REJECTED = 3 Just named constants. Boring. Rust enum: enum Status {   Pending,   Approved(String),   // Can hold DATA   Rejected { reason: String, code: u32 }, } Wait. WHAT? Enums can HOLD DATA. Each variant can be different. This changes everything. Real example I built today: enum PaymentMethod {   Cash,   CreditCard { number: String, cvv: u16 },   Crypto { wallet: String, coin: String }, } One type, multiple shapes. The compiler forces you to handle ALL cases. In Python/JS I'd use inheritance or dicts with a "type" field. Always worried I'd miss an edge case. In Rust? Compiler says "you forgot CreditCard case" and refuses to compile. Here's the mind-blowing part - Option and Result are just enums: enum Option<T> {   Some(T),   None, } enum Result<T, E> {   Ok(T),   Err(E), } No null. No exceptions. Just explicit data that can be one of several variants. This is called algebraic data types. Sounds fancy but it's just "enums that can hold different data per variant." Real talk: First hour I was confused. "Why not just use a struct?" Then I tried handling payment methods and it clicked. One function parameter that can be cash OR credit card OR crypto, and the compiler ensures I handle all three. In my CSV processing work, I have different record types (header, data, footer). Been using dicts with "type" keys. One typo and runtime error. With Rust enums? Compile error if I forget a case. Zero runtime surprises. --- 💡 TL;DR: - Enums in Rust can hold data (not just constants) - Each variant can have different types - Compiler enforces exhaustive handling - Option/Result are built on this pattern - Way more powerful than Python/JS enums Day 9/90 ✅ 🔗 Code: https://lnkd.in/eKBGKPbC #RustLang #LearnInPublic #100DaysOfCode #TypeSafety #AlgebraicDataTypes Have you used enums that hold data before? Which language? 👇

To view or add a comment, sign in

Explore content categories