liveBook · Manning

Option

As explained in Learn Rust in a Month of Lunches

An option type is a type that explicitly represents either a value of a specified type or the absence of a value.

Use `Option<T>` when a value might not exist. `Some(value)` means it is there; `None` means it is not. For example, not having a spouse is an absence, not an error. If an operation might fail instead, `Result` may be the better fit. section 5.2 section 5.2.1

`Option` is a generic enum: `Some(T)` holds a value of type `T`, while `None` holds no value. So `Option<i32>` can hold an integer or represent its absence. The integer is often called “wrapped” because it is inside the `Option`. section 5.2.1

Ask for a fifth item safely

Indexing a two-item vector at position 4 panics. Instead, a function returning `Option<i32>` can check the length first: return `None` if there are fewer than five items, or `Some(value[4])` otherwise. With `[1, 2]` and `[1, 2, 3, 4, 5]`, the results are `None` and `Some(5)`. section 5.2.1

fn try_take_fifth(value: Vec<i32>) -> Option<i32> {
    if value.len() < 5 {                            #1
        None
    } else {
        Some(value[4])
    }
}
 
fn main() {
    let small = vec![1, 2];
    let big = vec![1, 2, 3, 4, 5];
    println!("{:?}, {:?}", try_take_fifth(small), try_take_fifth(big));
}

The length check makes both possible outcomes explicit before indexing. section 5.2.1

To use the value, `match` on both possibilities: `Some(number)` gives you the number, and `None` lets you choose what to do without one. `.unwrap()` also extracts a value, but it panics on `None`; use it only when you are sure the value is `Some`. section 5.2.1

For a sequence of optional steps, `.and_then()` applies a function when the input is `Some` and passes `None` along. For instance, an array lookup can feed a number parse and then a character conversion. `.ok()` turns each `Result` into an `Option`, but discards error information: different failures all end as `None`. An iterator’s `.next()` likewise returns `Some` for an item and `None` when items run out. section 9.1.2 section 8.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains enum variants, checked returns, pattern matching, unwrap panics, and chained optional operations.
Examples
Uses a fifth-item vector lookup and an array lookup followed by number parsing and character conversion.
What it assumes
Builds on generics to read `Option<T>`, while defining `Some`, `None`, and wrapped values.
What you can do after
Build it from scratch: return `Option<i32>` for a checked lookup and handle `Some` and `None` with `match`.
How it connects
Connects Option to generics, Result, pattern matching, iterators, and method chaining.

Also explained in

Compare how 9 books explain option →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.