Auf Enum-Varianten matchen
Verwenden Sie match, um jeden Fall zu behandeln.
Auf Enum-Varianten matchen ist eine kostenlose Learn Rust Coding-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Learn Rust Coding-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Meet the match Expression
The match expression compares a value against a series of patterns and runs the code for the first one that fits.
It is the natural partner of enums: you can handle each variant in its own arm.
enum Light {
Red,
Green,
}
fn action(l: Light) {
match l {
Light::Red => println!("Stop"),
Light::Green => println!("Go"),
}
}Anatomy of a match Arm
Each arm has the form pattern => expression, and arms are separated by commas.
The pattern is what to match, and the expression after => runs when it matches. Here the pattern is a single enum variant.
match light {
Light::Red => println!("Stop"),
Light::Green => println!("Go"),
}A Full Matching Program
Here is a complete program that matches on a traffic light and prints an instruction.
Run it, then change the variant in main to watch a different arm fire.
enum TrafficLight {
Red,
Yellow,
Green,
}
fn main() {
let light = TrafficLight::Yellow;
match light {
TrafficLight::Red => println!("Stop"),
TrafficLight::Yellow => println!("Slow down"),
TrafficLight::Green => println!("Go"),
}
}match Must Be Exhaustive
Rust requires match to cover every possible variant. If you forget one, the program will not compile.
This is a powerful safety feature: add a new variant later and the compiler reminds you about every place that must handle it.
// This would FAIL to compile because
// the Green case is missing:
// match light {
// Light::Red => println!("Stop"),
// }The Catch-All with _
When you do not want to list every variant, use the underscore _ as a catch-all pattern. It matches anything not handled above.
Place it last, since arms are tried in order.
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn main() {
let c = Coin::Dime;
match c {
Coin::Penny => println!("1 cent"),
_ => println!("Some other coin"),
}
}match Returns a Value
match is an expression, so it produces a value you can store in a variable.
Every arm must return the same type. Notice there is no semicolon after each arm's expression here.
enum Coin {
Penny,
Quarter,
}
fn main() {
let coin = Coin::Quarter;
let cents = match coin {
Coin::Penny => 1,
Coin::Quarter => 25,
};
println!("{} cents", cents);
}Multi-Line Arm Bodies
An arm can run several statements by wrapping them in curly braces { ... }.
The last expression inside the braces is the value the arm produces.
match light {
Light::Red => {
println!("Caution!");
println!("Stop the car");
}
Light::Green => println!("Go"),
}Combining Patterns with |
Use the pipe | to match several variants in one arm. It reads as "or".
This avoids repeating the same body for variants that should behave identically.
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn main() {
let c = Coin::Nickel;
match c {
Coin::Penny | Coin::Nickel => println!("Small coin"),
_ => println!("Bigger coin"),
}
}match Versus if/else
You could chain if / else if to check variants, but match is clearer and safer.
With match, the compiler verifies you handled every case. A chain of if statements gives no such guarantee.
Matching and Printing Together
A common pattern is to turn a variant into a friendly string and print it.
Run this program and change the chosen direction to see the matching message.
enum Direction {
North,
South,
East,
West,
}
fn main() {
let d = Direction::West;
let name = match d {
Direction::North => "North",
Direction::South => "South",
Direction::East => "East",
Direction::West => "West",
};
println!("Heading {}", name);
}Order Matters
Arms are checked from top to bottom, and the first match wins. The rest are skipped.
This is why the catch-all _ must come last: if it were first, it would swallow every value before the specific arms could run.
Quick Check
Check your understanding of match.
Recap
You learned that match compares a value against patterns and runs the first matching arm.
It must be exhaustive, can use _ as a catch-all, can combine variants with |, and returns a value because it is an expression. Next you will give enum variants their own data.
Häufig gestellte Fragen
Ist die Lektion „Auf Enum-Varianten matchen“ kostenlos?
Ja — der vollständige Text von „Auf Enum-Varianten matchen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Learn Rust Coding-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Auf Enum-Varianten matchen“?
Verwenden Sie match, um jeden Fall zu behandeln. Du übst Learn Rust Coding mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Learn Rust Coding zu starten?
Keine Vorkenntnisse erforderlich. Learn Rust Coding auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „Auf Enum-Varianten matchen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Learn Rust Coding-Lektion Code schreiben und ausführen?
Ja. Jede Learn Rust Coding-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Ihr erstes Enum definieren
- Auf Enum-Varianten matchen
- Enums mit Daten
- Match-Guards und Bindings