1// If expressions have three uses, corresponding to the three types:
2// * bool
3// * ?T
4// * anyerror!T
5
6const expect = @import("std").testing.expect;
7const expectEqual = @import("std").testing.expectEqual;
8
9test "if expression" {
10 // If expressions are used instead of a ternary expression.
11 const a: u32 = 5;
12 const b: u32 = 4;
13 const result = if (a != b) 47 else 3089;
14 try expectEqual(result, 47);
15}
16
17test "if boolean" {
18 // If expressions test boolean conditions.
19 const a: u32 = 5;
20 const b: u32 = 4;
21 if (a != b) {
22 try expect(true);
23 } else if (a == 9) {
24 unreachable;
25 } else {
26 unreachable;
27 }
28}
29
30test "if error union" {
31 // If expressions test for errors.
32 // Note the |err| capture on the else.
33
34 const a: anyerror!u32 = 0;
35 if (a) |value| {
36 try expectEqual(value, 0);
37 } else |err| {
38 _ = err;
39 unreachable;
40 }
41
42 const b: anyerror!u32 = error.BadValue;
43 if (b) |value| {
44 _ = value;
45 unreachable;
46 } else |err| {
47 try expectEqual(err, error.BadValue);
48 }
49
50 // The else and |err| capture is strictly required.
51 if (a) |value| {
52 try expectEqual(value, 0);
53 } else |_| {}
54
55 // To check only the error value, use an empty block expression.
56 if (b) |_| {} else |err| {
57 try expectEqual(err, error.BadValue);
58 }
59
60 // Access the value by reference using a pointer capture.
61 var c: anyerror!u32 = 3;
62 if (c) |*value| {
63 value.* = 9;
64 } else |_| {
65 unreachable;
66 }
67
68 if (c) |value| {
69 try expectEqual(value, 9);
70 } else |_| {
71 unreachable;
72 }
73}
74
75// test