046_optionals2.zig 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. // We also introduce the handy `.?` shortcut:
  9. //
  10. // const foo = bar.?;
  11. //
  12. // is the same as
  13. //
  14. // const foo = bar orelse unreachable;
  15. //
  16. // Check out where we use this shortcut below to change control flow
  17. // based on if an optional value exists.
  18. //
  19. // Now let's make those elephant tails optional!
  20. //
  21. const std = @import("std");
  22. const Elephant = struct {
  23. letter: u8,
  24. tail: *Elephant = null, // Hmm... tail needs something...
  25. visited: bool = false,
  26. };
  27. pub fn main() void {
  28. var elephantA = Elephant{ .letter = 'A' };
  29. var elephantB = Elephant{ .letter = 'B' };
  30. var elephantC = Elephant{ .letter = 'C' };
  31. // Link the elephants so that each tail "points" to the next.
  32. linkElephants(&elephantA, &elephantB);
  33. linkElephants(&elephantB, &elephantC);
  34. // `linkElephants` will stop the program if you try and link an
  35. // elephant that doesn't exist! Uncomment and see what happens.
  36. // const missingElephant: ?*Elephant = null;
  37. // linkElephants(&elephantC, missingElephant);
  38. visitElephants(&elephantA);
  39. std.debug.print("\n", .{});
  40. }
  41. // If e1 and e2 are valid pointers to elephants,
  42. // this function links the elephants so that e1's tail "points" to e2.
  43. fn linkElephants(e1: ?*Elephant, e2: ?*Elephant) void {
  44. e1.?.tail = e2;
  45. }
  46. // This function visits all elephants once, starting with the
  47. // first elephant and following the tails to the next elephant.
  48. fn visitElephants(first_elephant: *Elephant) void {
  49. var e = first_elephant;
  50. while (!e.visited) {
  51. std.debug.print("Elephant {u}. ", .{e.letter});
  52. e.visited = true;
  53. // We should stop once we encounter a tail that
  54. // does NOT point to another element. What can
  55. // we put here to make that happen?
  56. // HINT: We want something similar to what `.?` does,
  57. // but instead of ending the program, we want to exit the loop...
  58. e = e.tail ???
  59. }
  60. }