Loading
0x50Lesson 6 of 17

Pattern matching with Option and enums

Use `match` and `if let` to handle optional values safely.

18 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • 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.

main.rs
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}
Output
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 XP

Trace an Option through control flow

Follow how a fallible parse returns either Some(number) or None.

Message 1 of 3Predicted 0/0
Input text
parse helper
caller match

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.

Exercise 1

Parse first integer token

+25 XP

Read one line and print the first integer token if present; otherwise print none.

  • Finds first number
  • No number
main.rs
Loading editor…

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…