Rust Option Example
Overview
This example shows a common Rust pattern for Option. The goal is to keep the code small enough to understand while still being useful in real projects.
Code example
fn find_user(id: u64) -> Option<&'static str> {
if id == 1 { Some("Alice") } else { None }
}
fn main() {
if let Some(name) = find_user(1) {
println!("{}", name);
}
}How it works
The example demonstrates how Rust combines strong typing with explicit ownership. Read the code from top to bottom and pay attention to where values are created, borrowed, moved, or consumed.
Common mistakes
- Forgetting whether a method takes ownership or borrows a value.
- Mixing references and owned values without clear intent.
- Ignoring compiler notes that point to the exact line that caused the issue.
When to use this pattern
Use this pattern when you want clear, explicit Rust code that can be checked at compile time and maintained safely as the project grows.
Related examples
- HashMap Example
- Result Error Handling Example
- Arc Mutex Example