ziglings/exercises/033_iferror.zig

57 lines
1.4 KiB
Zig
Raw Normal View History

2021-01-31 17:48:34 -05:00
//
// Let's revisit the very first error exercise. This time, we're going to
2021-08-28 10:55:34 -04:00
// look at an error-handling variation of the "if" statement.
2021-01-31 17:48:34 -05:00
//
// 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.
//
2021-08-28 10:57:51 -04:00
// if (foo) |value| {
// ...
// } else |err| switch(err) {
// ...
// }
//
2021-01-31 17:48:34 -05:00
const MyNumberError = error{
TooBig,
TooSmall,
};
const std = @import("std");
pub fn main() void {
const nums = [_]u8{ 2, 3, 4, 5, 6 };
2021-01-31 17:48:34 -05:00
for (nums) |num| {
std.debug.print("{}", .{num});
const n = numberMaybeFail(num);
2021-01-31 17:48:34 -05:00
if (n) |value| {
2021-06-30 17:56:42 -04:00
std.debug.print("={}. ", .{value});
2021-01-31 17:48:34 -05:00
} else |err| switch (err) {
2021-02-15 16:55:44 -05:00
MyNumberError.TooBig => std.debug.print(">4. ", .{}),
2021-01-31 17:48:34 -05:00
// Please add a match for TooSmall here and have it print: "<4. "
2024-01-10 02:52:58 -05:00
MyNumberError.TooSmall => std.debug.print("<4. ", .{}),
2021-01-31 17:48:34 -05:00
}
}
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 {
2021-02-15 16:55:44 -05:00
if (n > 4) return MyNumberError.TooBig;
if (n < 4) return MyNumberError.TooSmall;
2021-01-31 17:48:34 -05:00
return n;
}