022_errors2.zig 861 B

1234567891011121314151617181920212223242526272829
  1. //
  2. // A common case for errors is a situation where we're expecting to
  3. // have a value OR something has gone wrong. Take this example:
  4. //
  5. // var text: Text = getText("foo.txt");
  6. //
  7. // What happens if getText() can't find "foo.txt"? How do we express
  8. // this in Zig?
  9. //
  10. // Zig lets us make what's called an "error union" which is a value
  11. // which could either be a regular value OR an error from a set:
  12. //
  13. // var text: MyErrorSet!Text = getText("foo.txt");
  14. //
  15. // For now, let's just see if we can try making an error union!
  16. //
  17. const std = @import("std");
  18. const MyNumberError = error{TooSmall};
  19. pub fn main() void {
  20. var my_number: ??? = 5;
  21. // Looks like my_number will need to either store a number OR
  22. // an error. Can you set the type correctly above?
  23. my_number = MyNumberError.TooSmall;
  24. std.debug.print("I compiled!\n", .{});
  25. }