mirror of
https://github.com/ziglang/zig.git
synced 2024-11-14 16:13:24 +00:00
75 lines
1.6 KiB
Zig
75 lines
1.6 KiB
Zig
|
// If expressions have three uses, corresponding to the three types:
|
||
|
// * bool
|
||
|
// * ?T
|
||
|
// * anyerror!T
|
||
|
|
||
|
const expect = @import("std").testing.expect;
|
||
|
|
||
|
test "if expression" {
|
||
|
// If expressions are used instead of a ternary expression.
|
||
|
const a: u32 = 5;
|
||
|
const b: u32 = 4;
|
||
|
const result = if (a != b) 47 else 3089;
|
||
|
try expect(result == 47);
|
||
|
}
|
||
|
|
||
|
test "if boolean" {
|
||
|
// If expressions test boolean conditions.
|
||
|
const a: u32 = 5;
|
||
|
const b: u32 = 4;
|
||
|
if (a != b) {
|
||
|
try expect(true);
|
||
|
} else if (a == 9) {
|
||
|
unreachable;
|
||
|
} else {
|
||
|
unreachable;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
test "if error union" {
|
||
|
// If expressions test for errors.
|
||
|
// Note the |err| capture on the else.
|
||
|
|
||
|
const a: anyerror!u32 = 0;
|
||
|
if (a) |value| {
|
||
|
try expect(value == 0);
|
||
|
} else |err| {
|
||
|
_ = err;
|
||
|
unreachable;
|
||
|
}
|
||
|
|
||
|
const b: anyerror!u32 = error.BadValue;
|
||
|
if (b) |value| {
|
||
|
_ = value;
|
||
|
unreachable;
|
||
|
} else |err| {
|
||
|
try expect(err == error.BadValue);
|
||
|
}
|
||
|
|
||
|
// The else and |err| capture is strictly required.
|
||
|
if (a) |value| {
|
||
|
try expect(value == 0);
|
||
|
} else |_| {}
|
||
|
|
||
|
// To check only the error value, use an empty block expression.
|
||
|
if (b) |_| {} else |err| {
|
||
|
try expect(err == error.BadValue);
|
||
|
}
|
||
|
|
||
|
// Access the value by reference using a pointer capture.
|
||
|
var c: anyerror!u32 = 3;
|
||
|
if (c) |*value| {
|
||
|
value.* = 9;
|
||
|
} else |_| {
|
||
|
unreachable;
|
||
|
}
|
||
|
|
||
|
if (c) |value| {
|
||
|
try expect(value == 9);
|
||
|
} else |_| {
|
||
|
unreachable;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// test
|