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