if

if

if.zig

// If expressions have three uses, corresponding to the three types:
// * bool
// * ?T
// * anyerror!T

const assert = @import("std").debug.assert;

test "if boolean" {
    // If expressions test boolean conditions.
    const a: u32 = 5;
    const b: u32 = 4;
    if (a != b) {
        assert(true);
    } else if (a == 9) {
        unreachable;
    } else {
        unreachable;
    }

    // If expressions are used instead of a ternary expression.
    const result = if (a != b) 47 else 3089;
    assert(result == 47);
}

test "if optional" {
    // If expressions test for null.

    const a: ?u32 = 0;
    if (a) |value| {
        assert(value == 0);
    } else {
        unreachable;
    }

    const b: ?u32 = null;
    if (b) |value| {
        unreachable;
    } else {
        assert(true);
    }

    // The else is not required.
    if (a) |value| {
        assert(value == 0);
    }

    // To test against null only, use the binary equality operator.
    if (b == null) {
        assert(true);
    }

    // Access the value by reference using a pointer capture.
    var c: ?u32 = 3;
    if (c) |*value| {
        value.* = 2;
    }

    if (c) |value| {
        assert(value == 2);
    } 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| {
        assert(value == 0);
    } else |err| {
        unreachable;
    }

    const b: anyerror!u32 = error.BadValue;
    if (b) |value| {
        unreachable;
    } else |err| {
        assert(err == error.BadValue);
    }

    // The else and |err| capture is strictly required.
    if (a) |value| {
        assert(value == 0);
    } else |_| {}

    // To check only the error value, use an empty block expression.
    if (b) |_| {} else |err| {
        assert(err == error.BadValue);
    }

    // Access the value by reference using a pointer capture.
    var c: anyerror!u32 = 3;
    if (c) |*value| {
        value.* = 9;
    } else |err| {
        unreachable;
    }

    if (c) |value| {
        assert(value == 9);
    } else |err| {
        unreachable;
    }
}
``` ```
$ zig test if.zig
Test 1/3 if boolean...OK
Test 2/3 if optional...OK
Test 3/3 if error union...OK
All tests passed.

See also:

  • Optionals
  • Errors