Rust•Enums & Option
Rust Tuples, Enums, and the Option & Result Types
Rust replaces null pointers with the Option<T> enum (Some(T) | None) to guarantee null-safety.
Syntax
enum Option<T> { Some(T), None }
enum Result<T, E> { Ok(T), Err(E) }
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| Option<T> | Enum | Encapsulates optional value without null pointers. |
| Result<T, E> | Enum | Encapsulates success (Ok) or failure (Err). |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Rust locally:
// Custom algebraic enum with associated data
enum NodeStatus {
Online(String), // Hostname
Degraded { latency_ms: f64 },
Offline,
}
fn describe_node(status: &NodeStatus) {
match status {
NodeStatus::Online(host) => println!("[OK] Server online at {}", host),
NodeStatus::Degraded { latency_ms } => println!("[WARN] Degraded: {:.1}ms latency", latency_ms),
NodeStatus::Offline => println!("[CRITICAL] Node is offline!"),
}
}
fn main() {
let node1 = NodeStatus::Online(String::from("api-01"));
let node2 = NodeStatus::Degraded { latency_ms: 145.2 };
describe_node(&node1);
describe_node(&node2);
}Expected Output:
[OK] Server online at api-01 [WARN] Degraded: 145.2ms latency
How It Works: Step-by-Step
- Lines 2-6: Defines algebraic enum with associated data per variant.
- Lines 8-14: match destructures enum variants and extracts inner values.
Key Concepts
- Rust enums can hold data of different types inside each variant.
- Option eliminates null reference exceptions by requiring explicit handling of None.
Common Mistake: Calling .unwrap() on None
Unwrapping a None variant panics and terminates the thread immediately.
❌ Incorrect
let opt: Option<i32> = None; opt.unwrap(); // Thread panicked!
✅ Correct
let val = opt.unwrap_or(0); // Safe fallback
Related Rust Tutorials & Compiler
Rust Vectors (Vec<T>): Dynamic Heap Arrays and Slices
Master dynamic Vec<T> collections using vec! macro, push, pop, and indexing.
Rust HashMap: Key-Value Hash Tables and the Entry API
Store and look up key-value pairs using std::collections::HashMap and the Entry API.
Rust Strings: String vs &str and UTF-8 Slicing
Master String (growable heap string) vs &str (string slice) in Rust.
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.