Variants
- Rust course
- Beginner
- Lesson 78/115
- 4 min
Construct and use enum variants.
Working with variants
Enum values are passed to functions, returned, and taken apart with match. match checks at compile time that every variant is handled:
fn ters(y: Yon) -> Yon {
match y {
Yon::Kuzey => Yon::Guney,
Yon::Guney => Yon::Kuzey,
Yon::Dogu => Yon::Bati,
Yon::Bati => Yon::Dogu,
}
}If you add a new variant to the enum, every match that doesn't handle it fails to compile, so no case is forgotten.
Shortening with use, and methods
Methods are added to enums with impl too. To reduce long names, the variants can be brought into scope:
impl Yon {
fn yatay_mi(&self) -> bool {
use Yon::*;
matches!(self, Dogu | Bati)
}
}
println!("{}", Yon::Dogu.yatay_mi()); // trueThe matches! macro returns, as a bool, whether a value fits a pattern.
Practice Opposite direction
Write fn ters(y: Yon) -> Yon for the Yon enum with match. Print the results of ters(Yon::Kuzey) and ters(Yon::Dogu) with {:?}, separated by a space.
Starter code
#[derive(Debug)]
enum Yon {
Kuzey,
Guney,
Dogu,
Bati,
}
fn main() {
// buraya yaz
}Sample solution
#[derive(Debug)]
enum Yon {
Kuzey,
Guney,
Dogu,
Bati,
}
fn ters(y: Yon) -> Yon {
match y {
Yon::Kuzey => Yon::Guney,
Yon::Guney => Yon::Kuzey,
Yon::Dogu => Yon::Bati,
Yon::Bati => Yon::Dogu,
}
}
fn main() {
println!("{:?} {:?}", ters(Yon::Kuzey), ters(Yon::Dogu));
}Expected output
Guney Bati
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is needed to write <code>Yon::Kuzey == Yon::Kuzey</code>?
- #[derive(PartialEq)] Correct answer
- #[derive(Debug)]
- Nothing
- impl Yon
Explanation: The == operator needs the PartialEq trait; derive generates it automatically.
2 Pattern check
let y = Yon::Bati;
let yatay = ____(y, Yon::Dogu | Yon::Bati);
let y = Yon::Bati;
let yatay = matches!(y, Yon::Dogu | Yon::Bati);
Explanation: The matches! macro returns true if the pattern fits.
3 Syntax and role
| Term | Meaning |
|---|---|
match y { .. } |
Branching by variant |
matches!(y, ..) |
bool pattern test |
use Yon::* |
Brings variants into scope |
#[derive(PartialEq)] |
== support |