Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Error Handling with Option | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 18 of 50

·rust

Error Handling with Option

15 minutes

Course progress36%

Error Handling with Option

Option<T> represents a value that may or may not exist. It replaces null pointers from other languages, making the absence of a value explicit in the type system.

The Option Type

enum Option<T> {
    Some(T),
    None,
}

It's so common you don't need to prefix it with std::option::

Creating Options

fn main() {
    let some_number = Some(5);
    let none_number: Option<i32> = None;
    
    let x: Option<String> = Some(String::from(\"hello\"));
    let y: Option<String> = None;
}

Matching Options

The most explicit way to handle Option values:

fn find_even(nums: &[i32]) -> Option<i32> {
    for &n in nums {
        if n % 2 == 0 {
            return Some(n);
        }
    }
    None
}

fn main() {
    let numbers = [1, 3, 5, 8, 9];
    match find_even(&numbers) {
        Some(e) => println!(\"First even: {}\", e),
        None => println!(\"No even numbers\"),
    }
}

If Let Shorthand

For cases where you only care about one variant:

fn main() {
    let x: Option<i32> = Some(5);
    
    // Verbose match
    match x {
        Some(n) => println!(\"Value: {}\", n),
        None => (),
    }
    
    // Concise if let
    if let Some(n) = x {
        println!(\"Value: {}\", n);
    }
}

Option Methods

fn main() {
    let x: Option<i32> = Some(5);
    let y: Option<i32> = None;
    
    // Check existence
    println!(\"x.is_some(): {}\", x.is_some());  // true
    println!(\"y.is_none(): {}\", y.is_none());   // true
    
    // Extract with unwrap (panics if None)
    let val = x.unwrap();  // 5
    // let bad = y.unwrap();  // panics!
    
    // Safe extraction with default
    let val2 = y.unwrap_or(0);  // 0
    let val3 = y.unwrap_or_else(|| 42);  // 42
    
    // Transform values
    let doubled = x.map(|n| n * 2);  // Some(10)
    let none_doubled = y.map(|n| n * 2);  // None
    
    // Chain operations
    x.map(|n| n * 2)
     .map(|n| n + 1)
     .map(|n| println!(\"Result: {}\", n));  // None
}

Practical Example: Parsing Configuration

fn get_config_value(config: &std::collections::HashMap<String, String>, key: &str) -> Option<i32> {
    config.get(key)
        .and_then(|val| val.parse::<i32>().ok())
}

fn main() {
    let mut config = std::collections::HashMap::new();
    config.insert(String::from(\"timeout\"), String::from(\"30\"));
    
    match get_config_value(&config, \"timeout\") {
        Some(timeout) => println!(\"Timeout: {} seconds\", timeout),
        None => println!(\"Invalid or missing timeout\"),
    }
}

The Question Mark Operator

For propagating None values early:

fn main() {
    let x: Option<i32> = Some(5);
    
    // Traditional approach
    let y = match x {
        Some(val) => Some(val * 2),
        None => return None,
    };
    
    // But Option<T> expects the function to also return Option
}

fn double_optional(x: Option<i32>) -> Option<i32> {
    Some(x? * 2)  // Returns None if x is None
}

Why Option Over Null?

  1. Explicit: Absence is part of the type
  2. Safe: Can't access None as a value
  3. Composable: Chain operations with map, and_then
  4. Forces handling: Compiler requires you to handle None case
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities
Previous lessonCollections: HashMapContinue to lesson 19Error Handling with ResultBack to Rust Fundamentals curriculum