46_optionals2.zig 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // Now that we have optional types, we can apply them to structs.
  3. // The last time we checked in with our elephants, we had to link
  4. // all three of them together in a "circle" so that the last tail
  5. // linked to the first elephant. This is because we had NO CONCEPT
  6. // of a tail that didn't point to another elephant!
  7. //
  8. const std = @import("std"); // single quotes
  9. const Elephant = struct {
  10. letter: u8,
  11. tail: *Elephant = undefined, // <---- make this optional!
  12. visited: bool = false,
  13. };
  14. pub fn main() void {
  15. var elephantA = Elephant{ .letter = 'A' };
  16. var elephantB = Elephant{ .letter = 'B' };
  17. var elephantC = Elephant{ .letter = 'C' };
  18. // Link the elephants so that each tail "points" to the next.
  19. elephantA.tail = &elephantB;
  20. elephantB.tail = &elephantC;
  21. visitElephants(&elephantA);
  22. std.debug.print("\n", .{});
  23. }
  24. // This function visits all elephants once, starting with the
  25. // first elephant and following the tails to the next elephant.
  26. fn visitElephants(first_elephant: *Elephant) void {
  27. var e = first_elephant;
  28. while (!e.visited) {
  29. std.debug.print("Elephant {u}. ", .{e.letter});
  30. e.visited = true;
  31. // We should stop once we encounter a tail that
  32. // does NOT point to another element. What can
  33. // we put here to make that happen?
  34. if (e.tail == null) ???;
  35. e = e.tail.?;
  36. }
  37. }