057_unions3.zig 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // With tagged unions, it gets EVEN BETTER! If you don't have a
  3. // need for a separate enum, you can define an inferred enum with
  4. // your union all in one place. Just use the 'enum' keyword in
  5. // place of the tag type:
  6. //
  7. // const Foo = union(enum) {
  8. // small: u8,
  9. // medium: u32,
  10. // large: u64,
  11. // };
  12. //
  13. // Let's convert Insect. Doctor Zoraptera has already deleted the
  14. // explicit InsectStat enum for you!
  15. //
  16. const std = @import("std");
  17. const Insect = union(InsectStat) {
  18. flowers_visited: u16,
  19. still_alive: bool,
  20. };
  21. pub fn main() void {
  22. var ant = Insect{ .still_alive = true };
  23. var bee = Insect{ .flowers_visited = 17 };
  24. std.debug.print("Insect report! ", .{});
  25. printInsect(ant);
  26. printInsect(bee);
  27. std.debug.print("\n", .{});
  28. }
  29. fn printInsect(insect: Insect) void {
  30. switch (insect) {
  31. .still_alive => |a| std.debug.print("Ant alive is: {}. ", .{a}),
  32. .flowers_visited => |f| std.debug.print("Bee visited {} flowers. ", .{f}),
  33. }
  34. }
  35. // Inferred enums are neat, representing the tip of the iceberg
  36. // in the relationship between enums and unions. You can actually
  37. // coerce a union TO an enum (which gives you the active field
  38. // from the union as an enum). What's even wilder is that you can
  39. // coerce an enum to a union! But don't get too excited, that
  40. // only works when the union type is one of those weird zero-bit
  41. // types like void!
  42. //
  43. // Tagged unions, as with most ideas in computer science, have a
  44. // long history going back to the 1960s. However, they're only
  45. // recently becoming mainstream, particularly in system-level
  46. // programming languages. You might have also seen them called
  47. // "variants", "sum types", or even "enums"!