diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-03-12 18:59:46 -0500 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-03-12 18:59:46 -0500 |
commit | 6ad9774189fbd64b2f2c9519f4513ab34b0c3809 (patch) | |
tree | d6c90700131d5b28e898881f13e2a05612e4703f /exercises/046_optionals2.zig | |
parent | be36352572ddb18218e1830e49316c259dea5e8c (diff) | |
download | ziglings-6ad9774189fbd64b2f2c9519f4513ab34b0c3809.tar.gz ziglings-6ad9774189fbd64b2f2c9519f4513ab34b0c3809.tar.bz2 ziglings-6ad9774189fbd64b2f2c9519f4513ab34b0c3809.tar.xz ziglings-6ad9774189fbd64b2f2c9519f4513ab34b0c3809.zip |
"999 is enough for anybody" triple-zero padding (#18)
When I hit 999 exercises, I will finally have reached the ultimate
state of soteriological release and no more exercises will be needed.
The cycle will be complete. All that will be left is perfect quietude,
freedom, and highest happiness.
Diffstat (limited to 'exercises/046_optionals2.zig')
-rw-r--r-- | exercises/046_optionals2.zig | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/exercises/046_optionals2.zig b/exercises/046_optionals2.zig new file mode 100644 index 0000000..d3f65bb --- /dev/null +++ b/exercises/046_optionals2.zig @@ -0,0 +1,58 @@ +// +// Now that we have optional types, we can apply them to structs. +// The last time we checked in with our elephants, we had to link +// all three of them together in a "circle" so that the last tail +// linked to the first elephant. This is because we had NO CONCEPT +// of a tail that didn't point to another elephant! +// +// We also introduce the handy ".?" shortcut: +// +// const foo = bar.?; +// +// is the same as +// +// const foo = bar orelse unreachable; +// +// See if you can find where we use this shortcut below. +// +// Now let's make those elephant tails optional! +// +const std = @import("std"); + +const Elephant = struct { + letter: u8, + tail: *Elephant = null, // Hmm... tail needs something... + visited: bool = false, +}; + +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 (!e.visited) { + std.debug.print("Elephant {u}. ", .{e.letter}); + e.visited = true; + + // We should stop once we encounter a tail that + // does NOT point to another element. What can + // we put here to make that happen? + if (e.tail == null) ???; + + e = e.tail.?; + } +} |