Rust Enums: The Power of Algebraic Data Types
Rust's enums are far more powerful than other languages—each variant can carry different types of data. Combined with match expressions, they elegantly handle various cases. This makes enums ideal tools for expressing complex states and business logic.
Typical Patterns
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub enum OrderStatus {
Pending,
Paid,
Refunded { reason: String },
}
impl OrderStatus {
pub fn is_terminal(&self) -> bool {
matches!(self, OrderStatus::Refunded { .. })
}
}
The derive macro automatically implements common traits for enums, while serde provides powerful serialization capabilities.