blob 59309e53 (1087B) - Raw
1 const std = @import("std"); 2 const builtin = @import("builtin"); 3 const expect = std.testing.expect; 4 5 test "try on error union" { 6 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; 7 8 try tryOnErrorUnionImpl(); 9 comptime try tryOnErrorUnionImpl(); 10 } 11 12 fn tryOnErrorUnionImpl() !void { 13 const x = if (returnsTen()) |val| val + 1 else |err| switch (err) { 14 error.ItBroke, error.NoMem => 1, 15 error.CrappedOut => @as(i32, 2), 16 else => unreachable, 17 }; 18 try expect(x == 11); 19 } 20 21 fn returnsTen() anyerror!i32 { 22 return 10; 23 } 24 25 test "try without vars" { 26 const result1 = if (failIfTrue(true)) 1 else |_| @as(i32, 2); 27 try expect(result1 == 2); 28 29 const result2 = if (failIfTrue(false)) 1 else |_| @as(i32, 2); 30 try expect(result2 == 1); 31 } 32 33 fn failIfTrue(ok: bool) anyerror!void { 34 if (ok) { 35 return error.ItBroke; 36 } else { 37 return; 38 } 39 } 40 41 test "try then not executed with assignment" { 42 if (failIfTrue(true)) { 43 unreachable; 44 } else |err| { 45 try expect(err == error.ItBroke); 46 } 47 }