092_interfaces.zig 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // Remeber excerices 55-57 with tagged unions.
  3. //
  4. // (story/explanation from Dave)
  5. //
  6. const std = @import("std");
  7. const Ant = struct {
  8. still_alive: bool,
  9. pub fn print(self: Ant) void {
  10. std.debug.print("Ant is {s}.\n", .{if (self.still_alive) "alive" else "death"});
  11. }
  12. };
  13. const Bee = struct {
  14. flowers_visited: u16,
  15. pub fn print(self: Bee) void {
  16. std.debug.print("Bee visited {} flowers.\n", .{self.flowers_visited});
  17. }
  18. };
  19. const Grasshopper = struct {
  20. distance_hopped: u16,
  21. pub fn print(self: Grasshopper) void {
  22. std.debug.print("Grasshopper hopped {} m.\n", .{self.distance_hopped});
  23. }
  24. };
  25. const Insect = union(enum) {
  26. ant: Ant,
  27. bee: Bee,
  28. grasshopper: Grasshopper,
  29. pub fn print(self: Insect) void {
  30. switch (self) {
  31. inline else => |case| return case.print(),
  32. }
  33. }
  34. };
  35. pub fn main() !void {
  36. var my_insects = [_]Insect{ Insect{
  37. .ant = Ant{ .still_alive = true },
  38. }, Insect{
  39. .bee = Bee{ .flowers_visited = 17 },
  40. }, Insect{
  41. .grasshopper = Grasshopper{ .distance_hopped = 32 },
  42. } };
  43. // The daily situation report, what's going on in the garden
  44. try dailyReport(&my_insects);
  45. }
  46. // Through the interface we can keep a list of various objects
  47. // (in this case the insects of our garden) and even pass them
  48. // to a function without having to know the specific properties
  49. // of each or the object itself. This is really cool!
  50. fn dailyReport(insectReport: []Insect) !void {
  51. std.debug.print("Daily insect report:\n", .{});
  52. for (insectReport) |insect| {
  53. insect.print();
  54. }
  55. }
  56. // Interfaces... (explanation from Dave)