Structs, enums and matching
Enums model alternatives; match forces you to handle every one.
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.
#[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
EasyHandle an Option
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.