Rust Foundations·Ownership as a design tool

Structs, enums and matching

Enums model alternatives; match forces you to handle every one.

Intermediate 14 min read Lesson 7 of 300 Challenge included
What you will be able to do
  • Use structs for data that belongs together.
  • Use enums for a fixed set of alternatives.
  • Match on Option instead of assuming a value exists.

In plain English

Rust enums can hold data, which makes impossible states hard to represent. Option and Result are ordinary enums. Pattern matching destructures values and the compiler checks exhaustiveness.

state.rsRust
#[derive(Debug)]
enum Credential {
    Valid { score: u8 },
    Revoked { reason: String },
}

fn describe(credential: &Credential) -> String {
    match credential {
        Credential::Valid { score } => format!("Valid: {score}"),
        Credential::Revoked { reason } => format!("Revoked: {reason}"),
    }
}
Your turn

Handle an Option

Easy

Write a function that returns a label from Option<&str>, using "Unknown" for None.

RUST · starter
fn label(value: Option<&str>) -> &str {
    value.unwrap()
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What makes match safe in Rust?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 7 of 300 · 0% of course