diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-01-31 17:48:34 -0500 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-01-31 17:48:34 -0500 |
commit | c70fa5f58f5ca2dc010f00caee19027069a09131 (patch) | |
tree | 9f7d352065d282c15a75aa4c4168216e69a762f8 /32_iferror.zig | |
parent | 2de8a8c54d7090dd063bed8b6b283c2fcb452e43 (diff) | |
download | ziglings-c70fa5f58f5ca2dc010f00caee19027069a09131.tar.gz ziglings-c70fa5f58f5ca2dc010f00caee19027069a09131.tar.bz2 ziglings-c70fa5f58f5ca2dc010f00caee19027069a09131.tar.xz ziglings-c70fa5f58f5ca2dc010f00caee19027069a09131.zip |
Adding exs 27-32
Diffstat (limited to '32_iferror.zig')
-rw-r--r-- | 32_iferror.zig | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/32_iferror.zig b/32_iferror.zig new file mode 100644 index 0000000..ed92e94 --- /dev/null +++ b/32_iferror.zig @@ -0,0 +1,49 @@ +// +// Let's revisit the very first error exercise. This time, we're going to +// look at a special error-handling type of the "if" statement. +// +// if (foo) |value| { +// +// // foo was NOT an error; value is the non-error value of foo +// +// } else |err| { +// +// // foo WAS an error; err is the error value of foo +// +// } +// +// We'll take it even further and use a switch statement to handle +// the error types. +// +const MyNumberError = error{ + TooBig, + TooSmall, +}; + +const std = @import("std"); + +pub fn main() void { + var nums = [_]u8{2,3,4,5,6}; + + for (nums) |num| { + std.debug.print("{}", .{num}); + + var n = numberMaybeFail(num); + if (n) |value| { + std.debug.print("=4. ", .{}); + } else |err| switch (err) { + MyNumberError.TooBig => std.debug.print(">4. ", .{}), + // Please add a match for TooSmall here and have it print: "<4. " + } + } + + std.debug.print("\n", .{}); +} + +// This time we'll have numberMaybeFail() return an error union rather +// than a straight error. +fn numberMaybeFail(n: u8) MyNumberError!u8 { + if(n > 4) return MyNumberError.TooBig; + if(n < 4) return MyNumberError.TooSmall; + return n; +} |