Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/inferred_error_sets.zig

33 lines
838 B

const std = @import("std");
const debug = std.debug;
const testing = std.testing;
const MyError = error{
SomeError,
Overflow,
};
fn addExplicit(comptime T: type, a: T, b: T) MyError!T {
var res: T = undefined;
return if (@addWithOverflow(T, a, b, &res)) error.Overflow else res;
}
fn addInferred(comptime T: type, a: T, b: T) !T {
var res: T = undefined;
return if (@addWithOverflow(T, a, b, &res)) error.Overflow else res;
}
test "inferred error sets" {
if (addInferred(u32, 1, 2)) |res| {
testing.expectEqual(res, 3);
} else |_| {
unreachable;
}
if (addExplicit(u8, 255, 1)) |_| {
unreachable;
} else |err| switch (err) {
error.Overflow => debug.print("overflow occurred!\n", .{}),
else => debug.print("some other error occurred\n", .{}),
}
}