35_enums.zig 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // Remember that little mathematical virtual machine we made using the
  3. // "unreachable" statement? Well, there were two problems with the
  4. // way we were using op codes:
  5. //
  6. // 1. Having to remember op codes by number is no good.
  7. // 2. We had to use "unreachable" because Zig had no way of knowing
  8. // how many valid op codes there were.
  9. //
  10. // An "enum" is a Zig construct that lets you give names to numeric
  11. // values and store them in a set. They look a lot like error sets:
  12. //
  13. // const Fruit = enum{ apple, pear, orange };
  14. //
  15. // const my_fruit = Fruit.apple;
  16. //
  17. // Let's use an enum in place of the numbers we were using in the
  18. // previous version!
  19. //
  20. const std = @import("std");
  21. // Please complete the enum!
  22. const Ops = enum{ ??? };
  23. pub fn main() void {
  24. const operations = [_]Ops{
  25. Ops.inc,
  26. Ops.inc,
  27. Ops.inc,
  28. Ops.pow,
  29. Ops.dec,
  30. Ops.dec
  31. };
  32. var current_value: u32 = 0;
  33. for (operations) |op| {
  34. switch (op) {
  35. Ops.inc => { current_value += 1; },
  36. Ops.dec => { current_value -= 1; },
  37. Ops.pow => { current_value *= current_value; },
  38. // No "else" needed! Why is that?
  39. }
  40. std.debug.print("{} ", .{current_value});
  41. }
  42. std.debug.print("\n", .{});
  43. }