057_unions3.zig 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 InsectStat = enum{ flowers_visited, still_alive };
  18. const Insect = union(InsectStat){
  19. flowers_visited: u16,
  20. still_alive: bool,
  21. };
  22. pub fn main() void{
  23. const ant = Insect{ .still_alive = true };
  24. const bee = Insect{ .flowers_visited = 17 };
  25. std.debug.print("Insect report! ", .{});
  26. printInsect(ant);
  27. printInsect(bee);
  28. std.debug.print("\n", .{});
  29. }
  30. fn printInsect(insect: Insect) void{
  31. switch(insect){
  32. .still_alive => |a| std.debug.print("Ant alive is: {}. ", .{a}),
  33. .flowers_visited => |f| std.debug.print("Bee visited {} flowers. ", .{f}),
  34. }
  35. }
  36. // Inferred enums are neat, representing the tip of the iceberg
  37. // in the relationship between enums and unions. You can actually
  38. // coerce a union TO an enum (which gives you the active field
  39. // from the union as an enum). What's even wilder is that you can
  40. // coerce an enum to a union! But don't get too excited, that
  41. // only works when the union type is one of those weird zero-bit
  42. // types like void!
  43. //
  44. // Tagged unions, as with most ideas in computer science, have a
  45. // long history going back to the 1960s. However, they're only
  46. // recently becoming mainstream, particularly in system-level
  47. // programming languages. You might have also seen them called
  48. // "variants", "sum types", or even "enums"!