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();
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
fn tryOnErrorUnionImpl() {
|
2017-05-03 14:23:11 -07:00
|
|
|
const x = if (returnsTen()) |val| {
|
2017-02-02 14:09:27 -08:00
|
|
|
val + 1
|
|
|
|
} else |err| switch (err) {
|
|
|
|
error.ItBroke, error.NoMem => 1,
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
|
|
|
error ItBroke;
|
|
|
|
error NoMem;
|
|
|
|
error CrappedOut;
|
|
|
|
fn returnsTen() -> %i32 {
|
|
|
|
10
|
|
|
|
}
|
2017-02-05 15:58:58 -08:00
|
|
|
|
2017-05-23 18:38:31 -07:00
|
|
|
test "try without vars" {
|
2017-05-03 14:23:11 -07:00
|
|
|
const result1 = if (failIfTrue(true)) {
|
2017-02-05 15:58:58 -08:00
|
|
|
1
|
2017-05-03 14:23:11 -07:00
|
|
|
} else |_| {
|
2017-02-05 15:58:58 -08:00
|
|
|
i32(2)
|
|
|
|
};
|
|
|
|
assert(result1 == 2);
|
|
|
|
|
2017-05-03 14:23:11 -07:00
|
|
|
const result2 = if (failIfTrue(false)) {
|
2017-02-05 15:58:58 -08:00
|
|
|
1
|
2017-05-03 14:23:11 -07:00
|
|
|
} else |_| {
|
2017-02-05 15:58:58 -08:00
|
|
|
i32(2)
|
|
|
|
};
|
|
|
|
assert(result2 == 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn failIfTrue(ok: bool) -> %void {
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|