048_methods2.zig 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // Now that we've seen how methods work, let's see if we can help
  3. // our elephants out a bit more with some Elephant methods.
  4. //
  5. const std = @import("std");
  6. const Elephant = struct {
  7. letter: u8,
  8. tail: ?*Elephant = null,
  9. visited: bool = false,
  10. // New Elephant methods!
  11. pub fn getTail(self: *Elephant) *Elephant {
  12. return self.tail.?; // Remember, this is means "orelse unreachable"
  13. }
  14. pub fn hasTail(self: *Elephant) bool {
  15. return (self.tail != null);
  16. }
  17. pub fn visit(self: *Elephant) void {
  18. self.visited = true;
  19. }
  20. pub fn print(self: *Elephant) void {
  21. // Prints elephant letter and [v]isited
  22. var v: u8 = if (self.visited) 'v' else ' ';
  23. std.debug.print("{u}{u} ", .{ self.letter, v });
  24. }
  25. };
  26. pub fn main() void {
  27. var elephantA = Elephant{ .letter = 'A' };
  28. var elephantB = Elephant{ .letter = 'B' };
  29. var elephantC = Elephant{ .letter = 'C' };
  30. // Link the elephants so that each tail "points" to the next.
  31. elephantA.tail = &elephantB;
  32. elephantB.tail = &elephantC;
  33. visitElephants(&elephantA);
  34. std.debug.print("\n", .{});
  35. }
  36. // This function visits all elephants once, starting with the
  37. // first elephant and following the tails to the next elephant.
  38. fn visitElephants(first_elephant: *Elephant) void {
  39. var e = first_elephant;
  40. while (true) {
  41. e.print();
  42. e.visit();
  43. // Get the next elephant or stop.
  44. if (e.hasTail()) {
  45. e = e.???; // Which method do we want here?
  46. } else {
  47. break;
  48. }
  49. }
  50. }
  51. // Bonus: Zig's enums can also have methods! Can you find
  52. // one in the wild? If you can, mention it along with your
  53. // name or alias in a comment below this one and make a
  54. // pull request on GitHub for a piece of eternal Ziglings
  55. // glory. The first five (5) PRs will be accepted!
  56. //
  57. // 1) drforester - I found one in the Zig source:
  58. // https://github.com/ziglang/zig/blob/041212a41cfaf029dc3eb9740467b721c76f406c/src/Compilation.zig#L2495
  59. //
  60. // 2) bbuccianti - I found one!
  61. // https://github.com/ziglang/zig/blob/master/lib/std/debug.zig#L477
  62. //