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