2021-01-30 20:00:32 -05:00
|
|
|
//
|
2021-02-11 14:07:52 -05:00
|
|
|
// Believe it or not, sometimes things go wrong in programs.
|
2021-01-30 20:00:32 -05:00
|
|
|
//
|
|
|
|
// 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.
|
2021-02-15 16:55:44 -05:00
|
|
|
//
|
2021-01-30 20:00:32 -05:00
|
|
|
// We have the start of an error set, but we're missing the condition
|
|
|
|
// "TooSmall". Please add it where needed!
|
|
|
|
const MyNumberError = error{
|
|
|
|
TooBig,
|
2024-01-10 02:52:58 -05:00
|
|
|
TooSmall,
|
2021-01-30 20:00:32 -05:00
|
|
|
TooFour,
|
|
|
|
};
|
|
|
|
|
|
|
|
const std = @import("std");
|
|
|
|
|
|
|
|
pub fn main() void {
|
2021-12-25 23:24:01 -05:00
|
|
|
const nums = [_]u8{ 2, 3, 4, 5, 6 };
|
2021-01-30 20:00:32 -05:00
|
|
|
|
|
|
|
for (nums) |n| {
|
|
|
|
std.debug.print("{}", .{n});
|
|
|
|
|
|
|
|
const number_error = numberFail(n);
|
2021-02-15 16:55:44 -05:00
|
|
|
|
2021-01-30 20:00:32 -05:00
|
|
|
if (number_error == MyNumberError.TooBig) {
|
|
|
|
std.debug.print(">4. ", .{});
|
|
|
|
}
|
2024-01-10 02:52:58 -05:00
|
|
|
if (number_error == MyNumberError.TooSmall) {
|
2021-01-30 20:00:32 -05:00
|
|
|
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 {
|
2021-02-15 16:55:44 -05:00
|
|
|
if (n > 4) return MyNumberError.TooBig;
|
|
|
|
if (n < 4) return MyNumberError.TooSmall; // <---- this one is free!
|
2021-01-30 20:00:32 -05:00
|
|
|
return MyNumberError.TooFour;
|
|
|
|
}
|