Skip to main content
Be Bitwise
RustEnums & Pattern Matching

Option & Result

Option and Result are Rust's reply to null pointers and exceptions. Failure becomes something you handle on purpose, not something you ignore until it bites.

Option

Option<T> represents a value that might not exist:

rust
fn divide(a: f64, b: f64) -> Option<f64> {
if b == 0.0 {
None
} else {
Some(a / b)
}
}
match divide(10.0, 3.0) {
Some(result) => println!("Result: {:.2}", result),
None => println!("Cannot divide by zero"),
}

Option Methods

rust
let x: Option<i32> = Some(42);
// unwrap: panics if None
let value = x.unwrap(); // 42
// unwrap_or: default value
let value = x.unwrap_or(0); // 42
// map: transform the inner value
let doubled = x.map(|v| v * 2); // Some(84)
// and_then: chain operations that return Option
let result = x.and_then(|v| if v > 0 { Some(v) } else { None });

Result

Result<T, E> represents an operation that can succeed or fail:

rust
use std::fs;
fn read_username() -> Result<String, std::io::Error> {
fs::read_to_string("username.txt")
}
match read_username() {
Ok(name) => println!("Hello, {}", name),
Err(e) => println!("Error: {}", e),
}
Key Concept

Result is what stands in for exceptions. No throw-and-pray; you return a Result and the caller has to deal with it. The compiler keeps you honest — silently ignoring an error isn't an option.

The ? Operator

The ? operator propagates errors automatically:

rust
fn read_config() -> Result<String, std::io::Error> {
let username = fs::read_to_string("username.txt")?;
let config = fs::read_to_string("config.txt")?;
Ok(format!("{}: {}", username.trim(), config.trim()))
}

When read_to_string returns Err, ? short-circuits the whole function and propagates that error out of read_config. On Ok, it unwraps the value and carries on.

Spelled out, each ? is a match the compiler writes for you. The detail people miss is the From::from call on the error path. That's what lets a function returning Result<T, MyError> use ? on an io::Error, as long as MyError implements From<io::Error>:

In read_config the error types already match, so From::from is the identity conversion and compiles to nothing. Either way, the Err arm is an ordinary early return: a compare and a branch, which module 8 shows in the assembly.

Combining Option and Result

rust
fn parse_port(s: &str) -> Result<u16, String> {
s.parse::<u16>().map_err(|e| format!("Invalid port: {}", e))
}
fn get_port() -> Option<u16> {
let port_str = std::env::var("PORT").ok()?; // Result -> Option
port_str.parse().ok() // Result -> Option
}

Common Patterns

rust
// Provide a default
let port = std::env::var("PORT")
.unwrap_or_else(|_| String::from("8080"));
// Chain transformations
let length: Option<usize> = Some("hello")
.map(|s| s.len());
// Collect Results
let numbers: Result<Vec<i32>, _> = vec!["1", "2", "3"]
.iter()
.map(|s| s.parse::<i32>())
.collect();

Here's the toolkit in one function: ok_or turns a missing key into an error, map_err rewrites the parse error, and ? sends either straight back to the caller. Predict the four lines before you run it.

Try itSwap the first ? for .unwrap() and run again: the missing-port case now panics and takes the program down instead of returning an Err.
Rust (1.40.0)