enums

An enum is destructured similarly:

  1. // `allow` required to silence warnings because only
  2. // one variant is used.
  3. #[allow(dead_code)]
  4. enum Color {
  5. // These 3 are specified solely by their name.
  6. Red,
  7. Blue,
  8. Green,
  9. // These likewise tie `u32` tuples to different names: color models.
  10. RGB(u32, u32, u32),
  11. HSV(u32, u32, u32),
  12. HSL(u32, u32, u32),
  13. CMY(u32, u32, u32),
  14. CMYK(u32, u32, u32, u32),
  15. }
  16. fn main() {
  17. let color = Color::RGB(122, 17, 40);
  18. // TODO ^ Try different variants for `color`
  19. println!("What color is it?");
  20. // An `enum` can be destructured using a `match`.
  21. match color {
  22. Color::Red => println!("The color is Red!"),
  23. Color::Blue => println!("The color is Blue!"),
  24. Color::Green => println!("The color is Green!"),
  25. Color::RGB(r, g, b) =>
  26. println!("Red: {}, green: {}, and blue: {}!", r, g, b),
  27. Color::HSV(h, s, v) =>
  28. println!("Hue: {}, saturation: {}, value: {}!", h, s, v),
  29. Color::HSL(h, s, l) =>
  30. println!("Hue: {}, saturation: {}, lightness: {}!", h, s, l),
  31. Color::CMY(c, m, y) =>
  32. println!("Cyan: {}, magenta: {}, yellow: {}!", c, m, y),
  33. Color::CMYK(c, m, y, k) =>
  34. println!("Cyan: {}, magenta: {}, yellow: {}, key (black): {}!",
  35. c, m, y, k),
  36. // Don't need another arm because all variants have been examined
  37. }
  38. }

See also:

#[allow(...)], color models and enum