Option and Result
Option for maybe values
Some(v) holds a value; None means absent. No null pointer.
fn first(nums: &[i32]) -> Option<i32> {
nums.first().copied()
}
match first(&[10, 20]) {
Some(n) => println!("{n}"),
None => println!("empty"),
}
Result for success or error
Ok(v) is success; Err(e) is failure.
use std::fs;
fn read_hello() -> Result<String, std::io::Error> {
fs::read_to_string("hello.txt")
}
Unwrap carefully
unwrap panics on None/Err. Prefer match, ?, or unwrap_or while learning.
let n = first(&[]).unwrap_or(0);
println!("{n}");
Everyday pattern
- Return
Optionwhen absence is normal - Return
Resultwhen failure needs an error value - Use
?to propagate errors in functions that return Result - Avoid unchecked unwrap in library code
Comments
One comment per signed-in account. Comments are saved with this page’s URL.