From 6ad9774189fbd64b2f2c9519f4513ab34b0c3809 Mon Sep 17 00:00:00 2001 From: Dave Gauer Date: Fri, 12 Mar 2021 18:59:46 -0500 Subject: "999 is enough for anybody" triple-zero padding (#18) When I hit 999 exercises, I will finally have reached the ultimate state of soteriological release and no more exercises will be needed. The cycle will be complete. All that will be left is perfect quietude, freedom, and highest happiness. --- exercises/021_errors.zig | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 exercises/021_errors.zig (limited to 'exercises/021_errors.zig') diff --git a/exercises/021_errors.zig b/exercises/021_errors.zig new file mode 100644 index 0000000..cbb5ac8 --- /dev/null +++ b/exercises/021_errors.zig @@ -0,0 +1,46 @@ +// +// Believe it or not, sometimes things go wrong in programs. +// +// In Zig, an error is a value. Errors are named so we can identify +// things that can go wrong. Errors are created in "error sets", which +// are just a collection of named errors. +// +// We have the start of an error set, but we're missing the condition +// "TooSmall". Please add it where needed! +const MyNumberError = error{ + TooBig, + ???, + TooFour, +}; + +const std = @import("std"); + +pub fn main() void { + var nums = [_]u8{ 2, 3, 4, 5, 6 }; + + for (nums) |n| { + std.debug.print("{}", .{n}); + + const number_error = numberFail(n); + + if (number_error == MyNumberError.TooBig) { + std.debug.print(">4. ", .{}); + } + if (???) { + std.debug.print("<4. ", .{}); + } + if (number_error == MyNumberError.TooFour) { + std.debug.print("=4. ", .{}); + } + } + + std.debug.print("\n", .{}); +} + +// Notice how this function can return any member of the MyNumberError +// error set. +fn numberFail(n: u8) MyNumberError { + if (n > 4) return MyNumberError.TooBig; + if (n < 4) return MyNumberError.TooSmall; // <---- this one is free! + return MyNumberError.TooFour; +} -- cgit v1.2.3-ZIG