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 char in KeyPress, or x and y in Click only works within a match or an if let statement.
  • match and if let inspect a hidden discriminant field in the enum.
  • It is possible to retrieve the discriminant by calling std::mem::discriminant()
  • This is useful, for example, if implementing PartialEq for structs where comparing field values doesn’t affect equality.
  • WebEvent::Click { ... } is not exactly the same as WebEvent::Click(Click) with a top level struct Click { ... }. The inlined version cannot implement traits, for example.