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








