023_errors3.zig 621 B

1234567891011121314151617181920212223242526272829
  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. const a: u32 = addTwenty(44) catch 22;
  13. const b: u32 = addTwenty(4) catch 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) MyNumberError!u32{
  19. if(n < 5){
  20. return MyNumberError.TooSmall;
  21. }else{
  22. return n + 20;
  23. }
  24. }