Pattern matching with Option and enums
Use `match` and `if let` to handle optional values safely.
- Handle
Option<T>without null checks.
Option<T> represents either Some(value) or None. Pattern matching forces you to handle both, so missing-data bugs become compile errors instead of runtime surprises.
1fn first_char(text: &str) -> Option<char> {
2 text.chars().next()
3}
4
5fn main() {
6 match first_char("rust") {
7 Some(ch) => println!("{}", ch),
8 None => println!("(empty)"),
9 }
10}r
Use match for explicit exhaustive handling, and if let when you care about one case and can ignore the rest.
Try it
Up to 15 XPTrace an Option through control flow
Follow how a fallible parse returns either Some(number) or None.
Key takeaways
Handle
Option<T>without null checks.Rust uses types and ownership rules to prevent common bugs.
Small experiments build intuition quickly.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Rust
These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.
Parse first integer token
Read one line and print the first integer token if present; otherwise print none.
- Finds first number
- No number
Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…