048_methods2.zig 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 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. const 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. // This links 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. // This gets the next elephant or stops:
  44. // which method do we want here?
  45. e = if (e.hasTail()) e.??? else break;
  46. }
  47. }
  48. // Zig's enums can also have methods! This comment originally asked
  49. // if anyone could find instances of enum methods in the wild. The
  50. // first five pull requests were accepted and here they are:
  51. //
  52. // 1) drforester - I found one in the Zig source:
  53. // https://github.com/ziglang/zig/blob/041212a41cfaf029dc3eb9740467b721c76f406c/src/Compilation.zig#L2495
  54. //
  55. // 2) bbuccianti - I found one!
  56. // https://github.com/ziglang/zig/blob/6787f163eb6db2b8b89c2ea6cb51d63606487e12/lib/std/debug.zig#L477
  57. //
  58. // 3) GoldsteinE - Found many, here's one
  59. // https://github.com/ziglang/zig/blob/ce14bc7176f9e441064ffdde2d85e35fd78977f2/lib/std/target.zig#L65
  60. //
  61. // 4) SpencerCDixon - Love this language so far :-)
  62. // https://github.com/ziglang/zig/blob/a502c160cd51ce3de80b3be945245b7a91967a85/src/zir.zig#L530
  63. //
  64. // 5) tomkun - here's another enum method
  65. // https://github.com/ziglang/zig/blob/4ca1f4ec2e3ae1a08295bc6ed03c235cb7700ab9/src/codegen/aarch64.zig#L24