046_optionals2.zig 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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(&elephantC, &elephantA);
  35. // `linkElephants` will stop the program if you try and link an
  36. // elephant that doesn't exist! Uncomment and see what happens.
  37. // const missingElephant: ?*Elephant = null;
  38. // linkElephants(&elephantC, missingElephant);
  39. visitElephants(&elephantA);
  40. std.debug.print("\n", .{});
  41. }
  42. // If e1 and e2 are valid pointers to elephants,
  43. // this function links the elephants so that e1's tail "points" to e2.
  44. fn linkElephants(e1: ?*Elephant, e2: ?*Elephant) void{
  45. e1.?.tail = e2.?;
  46. }
  47. // This function visits all elephants once, starting with the
  48. // first elephant and following the tails to the next elephant.
  49. fn visitElephants(first_elephant: *Elephant) void{
  50. var e = first_elephant;
  51. while(!e.visited){
  52. std.debug.print("Elephant {u}. ", .{e.letter});
  53. e.visited = true;
  54. // We should stop once we encounter a tail that
  55. // does NOT point to another element. What can
  56. // we put here to make that happen?
  57. // HINT: We want something similar to what `.?` does,
  58. // but instead of ending the program, we want to exit the loop...
  59. e = e.tail orelse break;
  60. }
  61. }