| 1 | const expect = @import("std").testing.expect; |
| 2 | const expectEqual = @import("std").testing.expectEqual; |
| 3 | |
| 4 | test "if optional" { |
| 5 | // If expressions test for null. |
| 6 | |
| 7 | const a: ?u32 = 0; |
| 8 | if (a) |value| { |
| 9 | try expectEqual(0, value); |
| 10 | } else { |
| 11 | unreachable; |
| 12 | } |
| 13 | |
| 14 | const b: ?u32 = null; |
| 15 | if (b) |_| { |
| 16 | unreachable; |
| 17 | } else { |
| 18 | try expect(true); |
| 19 | } |
| 20 | |
| 21 | // The else is not required. |
| 22 | if (a) |value| { |
| 23 | try expectEqual(0, value); |
| 24 | } |
| 25 | |
| 26 | // To test against null only, use the binary equality operator. |
| 27 | if (b == null) { |
| 28 | try expect(true); |
| 29 | } |
| 30 | |
| 31 | // Access the value by reference using a pointer capture. |
| 32 | var c: ?u32 = 3; |
| 33 | if (c) |*value| { |
| 34 | value.* = 2; |
| 35 | } |
| 36 | |
| 37 | if (c) |value| { |
| 38 | try expectEqual(2, value); |
| 39 | } else { |
| 40 | unreachable; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | test "if error union with optional" { |
| 45 | // If expressions test for errors before unwrapping optionals. |
| 46 | // The |optional_value| capture's type is ?u32. |
| 47 | |
| 48 | const a: anyerror!?u32 = 0; |
| 49 | if (a) |optional_value| { |
| 50 | try expectEqual(0, optional_value.?); |
| 51 | } else |err| { |
| 52 | _ = err; |
| 53 | unreachable; |
| 54 | } |
| 55 | |
| 56 | const b: anyerror!?u32 = null; |
| 57 | if (b) |optional_value| { |
| 58 | try expectEqual(null, optional_value); |
| 59 | } else |_| { |
| 60 | unreachable; |
| 61 | } |
| 62 | |
| 63 | const c: anyerror!?u32 = error.BadValue; |
| 64 | if (c) |optional_value| { |
| 65 | _ = optional_value; |
| 66 | unreachable; |
| 67 | } else |err| { |
| 68 | try expectEqual(error.BadValue, err); |
| 69 | } |
| 70 | |
| 71 | // Access the value by reference by using a pointer capture each time. |
| 72 | var d: anyerror!?u32 = 3; |
| 73 | if (d) |*optional_value| { |
| 74 | if (optional_value.*) |*value| { |
| 75 | value.* = 9; |
| 76 | } |
| 77 | } else |_| { |
| 78 | unreachable; |
| 79 | } |
| 80 | |
| 81 | if (d) |optional_value| { |
| 82 | try expectEqual(9, optional_value.?); |
| 83 | } else |_| { |
| 84 | unreachable; |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // test |