diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-02-28 13:23:22 -0500 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-02-28 13:23:22 -0500 |
commit | b12afaa577e5f9b0c3bf922ec5c1ab15893c7378 (patch) | |
tree | c8a5be6d30f4b44ea6124064fcf3e399876ab661 /exercises/48_methods2.zig | |
parent | febc9dfecb5285cdaa9f4e9edb4d8331a1f1350c (diff) | |
download | ziglings-b12afaa577e5f9b0c3bf922ec5c1ab15893c7378.tar.gz ziglings-b12afaa577e5f9b0c3bf922ec5c1ab15893c7378.tar.bz2 ziglings-b12afaa577e5f9b0c3bf922ec5c1ab15893c7378.tar.xz ziglings-b12afaa577e5f9b0c3bf922ec5c1ab15893c7378.zip |
Added ex 48, additional comment on 46
Diffstat (limited to 'exercises/48_methods2.zig')
-rw-r--r-- | exercises/48_methods2.zig | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/exercises/48_methods2.zig b/exercises/48_methods2.zig new file mode 100644 index 0000000..b9477da --- /dev/null +++ b/exercises/48_methods2.zig @@ -0,0 +1,68 @@ +// +// Now that we've seen how methods work, let's see if we can help +// our elephants out a bit more with some Elephant methods. +// +const std = @import("std"); + +const Elephant = struct { + letter: u8, + tail: ?*Elephant = null, + visited: bool = false, + + // New Elephant methods! + pub fn getTail(self: *Elephant) *Elephant { + return self.tail.?; // Remember, this is means "orelse unreachable" + } + + pub fn hasTail(self: *Elephant) bool { + return (self.tail != null); + } + + pub fn visit(self: *Elephant) void { + self.visited = true; + } + + pub fn print(self: *Elephant) void { + // Prints elephant letter and (V)isited or (U)nvisited. + var v: u8 = if (self.visited) 'V' else 'U'; + std.debug.print("Elephant {u} ({u}). ", .{ self.letter, v}); + } +}; + +pub fn main() void { + var elephantA = Elephant{ .letter = 'A' }; + var elephantB = Elephant{ .letter = 'B' }; + var elephantC = Elephant{ .letter = 'C' }; + + // Link the elephants so that each tail "points" to the next. + elephantA.tail = &elephantB; + elephantB.tail = &elephantC; + + visitElephants(&elephantA); + + std.debug.print("\n", .{}); +} + +// This function visits all elephants once, starting with the +// first elephant and following the tails to the next elephant. +fn visitElephants(first_elephant: *Elephant) void { + var e = first_elephant; + + while (true) { + e.print(); + e.visit(); + + // Get the next elephant or stop. + if (e.hasTail()) { + e = e.???; // Which method do we want here? + } else { + break; + } + } +} + +// Bonus: Zig's enums can also have methods! Can you find +// one in the wild? If you can, mention it along with your +// name or alias in a comment below this one and make a +// pull request on GitHub for a piece of eternal Ziglings +// glory. The first five (5) PRs will be accepted! |