2017-02-03 06:09:27 +08:00
|
|
|
const assert = @import("std").debug.assert;
|
|
|
|
|
2017-05-24 09:38:31 +08:00
|
|
|
test "try on error union" {
|
2017-02-28 16:07:11 +08:00
|
|
|
tryOnErrorUnionImpl();
|
|
|
|
comptime tryOnErrorUnionImpl();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2018-01-25 17:10:11 +08:00
|
|
|
fn tryOnErrorUnionImpl() void {
|
2017-12-22 13:50:30 +08:00
|
|
|
const x = if (returnsTen()) |val|
|
2017-02-03 06:09:27 +08:00
|
|
|
val + 1
|
2017-12-22 13:50:30 +08:00
|
|
|
else |err| switch (err) {
|
2017-02-03 06:09:27 +08:00
|
|
|
error.ItBroke, error.NoMem => 1,
|
|
|
|
error.CrappedOut => i32(2),
|
2017-05-08 00:07:35 +08:00
|
|
|
else => unreachable,
|
2017-02-03 06:09:27 +08:00
|
|
|
};
|
|
|
|
assert(x == 11);
|
|
|
|
}
|
|
|
|
|
2018-02-03 03:26:14 +08:00
|
|
|
fn returnsTen() error!i32 {
|
2017-12-22 13:50:30 +08:00
|
|
|
return 10;
|
2017-02-03 06:09:27 +08:00
|
|
|
}
|
2017-02-06 07:58:58 +08:00
|
|
|
|
2017-05-24 09:38:31 +08:00
|
|
|
test "try without vars" {
|
2017-12-22 13:50:30 +08:00
|
|
|
const result1 = if (failIfTrue(true)) 1 else |_| i32(2);
|
2017-02-06 07:58:58 +08:00
|
|
|
assert(result1 == 2);
|
|
|
|
|
2017-12-22 13:50:30 +08:00
|
|
|
const result2 = if (failIfTrue(false)) 1 else |_| i32(2);
|
2017-02-06 07:58:58 +08:00
|
|
|
assert(result2 == 1);
|
|
|
|
}
|
|
|
|
|
2018-02-03 03:26:14 +08:00
|
|
|
fn failIfTrue(ok: bool) error!void {
|
2017-02-06 07:58:58 +08:00
|
|
|
if (ok) {
|
|
|
|
return error.ItBroke;
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2017-02-28 16:07:11 +08:00
|
|
|
|
2017-05-02 10:37:34 +08:00
|
|
|
test "try then not executed with assignment" {
|
2017-05-04 05:23:11 +08:00
|
|
|
if (failIfTrue(true)) {
|
2017-05-02 10:37:34 +08:00
|
|
|
unreachable;
|
|
|
|
} else |err| {
|
|
|
|
assert(err == error.ItBroke);
|
|
|
|
}
|
|
|
|
}
|