14.6 Best Practices
To make the most of Option<T>, keep these guidelines in mind.
14.6.1 When to Use Option<T>
- Potentially Empty Return Values: If your function might not produce meaningful output.
- Configuration Data: For optional fields in configuration structures.
- Validation: When inputs may be incomplete or invalid.
- Data Structures: For fields that can legitimately be absent.
14.6.2 Avoiding Common Pitfalls
- Avoid Excessive
unwrap(): Uncontrolled calls tounwrap()can lead to panics and undermine Rust’s safety. - Embrace Combinators: Methods like
map,and_then,filter, andunwrap_oreliminate boilerplate. - Use
?Judiciously: It simplifies early returns but can obscure logic if overused. - Handle
NoneProperly: The whole point ofOptionis to force a decision around missing data.
// Nested matching:
match a {
Some(x) => match x.b {
Some(y) => Some(y.c),
None => None,
},
None => None,
}
// Using combinators:
a.and_then(|x| x.b).map(|y| y.c)