PR3-Rust-SS26/E-enums/05_verschachtelt.rs

56 lines
1.2 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// Patterns können beliebig tief verschachtelt werden:
// Structs in Enums in Options alles in einem match.
enum Inhalt {
Text(String),
Zahl(i32),
}
struct Paket {
absender: String,
inhalt: Option<Inhalt>,
}
fn oeffne(p: &Paket) {
match p {
// Option UND Enum gleichzeitig destrukturieren
Paket {
absender,
inhalt: Some(Inhalt::Text(t)),
} => {
println!("Von {absender}: Text \"{t}\"");
}
Paket {
absender,
inhalt: Some(Inhalt::Zahl(n)),
} => {
println!("Von {absender}: Zahl {n}");
}
// .. deckt restliche Felder ab (hier: absender)
Paket { inhalt: None, .. } => {
println!("Leeres Paket.");
}
}
}
fn main() {
let pakete = vec![
Paket {
absender: "Alice".into(),
inhalt: Some(Inhalt::Text("Hallo".into())),
},
Paket {
absender: "Bob".into(),
inhalt: Some(Inhalt::Zahl(99)),
},
Paket {
absender: "Eve".into(),
inhalt: None,
},
];
for p in &pakete {
oeffne(p);
}
}