Variant Payloads
You can define richer enums where the variants carry data. You can then use the match statement to extract the data from each variant:
1. enum WebEvent {
2. PageLoad, // Variant without payload
3. KeyPress(char), // Tuple struct variant
4. Click { x: i64, y: i64 }, // Full struct variant
5. }
7. #[rustfmt::skip]
8. fn inspect(event: WebEvent) {
9. match event {
10. WebEvent::PageLoad => println!("page loaded"),
11. WebEvent::KeyPress(c) => println!("pressed '{c}'"),
12. WebEvent::Click { x, y } => println!("clicked at x={x}, y={y}"),
13. }
14. }
16. fn main() {
17. let load = WebEvent::PageLoad;
18. let press = WebEvent::KeyPress('x');
19. let click = WebEvent::Click { x: 20, y: 80 };
21. inspect(load);
22. inspect(press);
23. inspect(click);
24. }
- In the above example, accessing the
charinKeyPress, orxandyinClickonly works within amatchor anif letstatement. matchandif letinspect a hidden discriminant field in theenum.- It is possible to retrieve the discriminant by calling
std::mem::discriminant() - This is useful, for example, if implementing
PartialEqfor structs where comparing field values doesn’t affect equality. WebEvent::Click { ... }is not exactly the same asWebEvent::Click(Click)with a top levelstruct Click { ... }. The inlined version cannot implement traits, for example.
