Missing is a real case.
Express absence directly instead of using sentinel values.
01 Understand the contract
Option<T> is either Some(T) or None. It distinguishes a present value from absence without borrowing a magic integer or empty string for that role. match and if let let you handle the variants. map transforms the present case, and_then chains optional operations, and unwrap_or supplies a fallback. Use unwrap only where an invariant justifies a panic; user input and lookup misses normally deserve a handled result. An Option<&T> can represent a borrowed lookup without cloning.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let values = [10, 20];
let doubled = values.get(1).map(|value| value * 2);
println!("present={doubled:?}");
println!("fallback={}", values.get(8).copied().unwrap_or(0));
if let Some(first) = values.first() {
println!("first={first}");
}
}present=Some(40) fallback=0 first=10
- 1
get returns an optional borrowed element.
- 2
map transforms only the Some case.
- 3
copied converts Option<&i32> to Option<i32> before applying a fallback.
cargo run -p lesson_option03 Mind the boundary
04 Your next build
Return the first nonempty string from a slice, borrowing the text.
Reveal one possible solution +
fn first_nonempty(values: &[String]) -> Option<&str> {
values.iter().find(|s| !s.is_empty()).map(String::as_str)
}
fn main() {
assert_eq!(first_nonempty(&[]), None);
let v = vec![String::new(), "ready".into()];
assert_eq!(first_nonempty(&v), Some("ready"));
}05 Check your reasoning
Which variant represents absence?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.