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/while_with_error_unions.zig

24 lines
599 B

const std = @import("std");
const testing = std.testing;
// when the else |x| form is used, x must be an error union
var numbers_left: u32 = undefined;
test "while error union capture" {
var sum: u32 = 0;
numbers_left = 3;
while (eventuallyErrorSequence()) |value| {
sum += value;
} else |err| {
testing.expectEqual(err, error.NoMoreNumbers);
}
testing.expectEqual(sum, 3);
}
fn eventuallyErrorSequence() anyerror!u32 {
return if (numbers_left == 0) error.NoMoreNumbers else blk: {
numbers_left -= 1;
break :blk numbers_left;
};
}