023_errors3.zig 622 B

12345678910111213141516171819202122232425262728
  1. //
  2. // One way to deal with error unions is to "catch" any error and
  3. // replace it with a default value.
  4. //
  5. // foo = canFail() catch 6;
  6. //
  7. // If canFail() fails, foo will equal 6.
  8. //
  9. const std = @import("std");
  10. const MyNumberError = error{TooSmall};
  11. pub fn main() void {
  12. var a: u32 = addTwenty(44) catch 22;
  13. var b: u32 = addTwenty(4) ??? 22;
  14. std.debug.print("a={}, b={}\n", .{ a, b });
  15. }
  16. // Please provide the return type from this function.
  17. // Hint: it'll be an error union.
  18. fn addTwenty(n: u32) ??? {
  19. if (n < 5) {
  20. return MyNumberError.TooSmall;
  21. } else {
  22. return n + 20;
  23. }
  24. }