045_optionals.zig 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //
  2. // Sometimes you know that a variable might hold a value or
  3. // it might not. Zig has a neat way of expressing this idea
  4. // called Optionals. An optional type just has a '?' like this:
  5. //
  6. // var foo: ?u32 = 10;
  7. //
  8. // Now foo can store a u32 integer OR null (a value storing
  9. // the cosmic horror of a value NOT EXISTING!)
  10. //
  11. // foo = null;
  12. //
  13. // if (foo == null) beginScreaming();
  14. //
  15. // Before we can use the optional value as the non-null type
  16. // (a u32 integer in this case), we need to guarantee that it
  17. // isn't null. One way to do this is to THREATEN IT with the
  18. // "orelse" statement.
  19. //
  20. // var bar = foo orelse 2;
  21. //
  22. // Here, bar will either equal the u32 integer value stored in
  23. // foo, or it will equal 2 if foo was null.
  24. //
  25. const std = @import("std");
  26. pub fn main() void {
  27. const result = deepThought();
  28. // Please threaten the result so that answer is either the
  29. // integer value from deepThought() OR the number 42:
  30. const answer: u8 = result;
  31. std.debug.print("The Ultimate Answer: {}.\n", .{answer});
  32. }
  33. fn deepThought() ?u8 {
  34. // It seems Deep Thought's output has declined in quality.
  35. // But we'll leave this as-is. Sorry Deep Thought.
  36. return null;
  37. }
  38. // Blast from the past:
  39. //
  40. // Optionals are a lot like error union types which can either
  41. // hold a value or an error. Likewise, the orelse statement is
  42. // like the catch statement used to "unwrap" a value or supply
  43. // a default value:
  44. //
  45. // var maybe_bad: Error!u32 = Error.Evil;
  46. // var number: u32 = maybe_bad catch 0;
  47. //