056_unions2.zig 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // It is really quite inconvenient having to manually keep track
  3. // of the active field in our union, isn't it?
  4. //
  5. // Thankfully, Zig also has "tagged unions", which allow us to
  6. // store an enum value within our union representing which field
  7. // is active.
  8. //
  9. // const FooTag = enum{ small, medium, large };
  10. //
  11. // const Foo = union(FooTag) {
  12. // small: u8,
  13. // medium: u32,
  14. // large: u64,
  15. // };
  16. //
  17. // Now we can use a switch directly on the union to act on the
  18. // active field:
  19. //
  20. // var f = Foo{ .small = 10 };
  21. //
  22. // switch (f) {
  23. // .small => |my_small| do_something(my_small),
  24. // .medium => |my_medium| do_something(my_medium),
  25. // .large => |my_large| do_something(my_large),
  26. // }
  27. //
  28. // Let's make our Insects use a tagged union (Doctor Zoraptera
  29. // approves).
  30. //
  31. const std = @import("std");
  32. const InsectStat = enum { flowers_visited, still_alive };
  33. const Insect = union(InsectStat) {
  34. flowers_visited: u16,
  35. still_alive: bool,
  36. };
  37. pub fn main() void {
  38. const ant = Insect{ .still_alive = true };
  39. const bee = Insect{ .flowers_visited = 16 };
  40. std.debug.print("Insect report! ", .{});
  41. // Could it really be as simple as just passing the union?
  42. printInsect(???);
  43. printInsect(???);
  44. std.debug.print("\n", .{});
  45. }
  46. fn printInsect(insect: Insect) void {
  47. switch (???) {
  48. .still_alive => |a| std.debug.print("Ant alive is: {}. ", .{a}),
  49. .flowers_visited => |f| std.debug.print("Bee visited {} flowers. ", .{f}),
  50. }
  51. }
  52. // By the way, did unions remind you of optional values and errors?
  53. // Optional values are basically "null unions" and errors use "error
  54. // union types". Now we can add our own unions to the mix to handle
  55. // whatever situations we might encounter:
  56. // union(Tag) { value: u32, toxic_ooze: void }