Rust:Rust Tuples, Enums, and the Option & Result Types
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:

ParameterTypeDescription
Option<T>EnumEncapsulates optional value without null pointers.
Result<T, E>EnumEncapsulates success (Ok) or failure (Err).

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler