Array Literals

An array literal creates an array value.

Array Literals

An array literal creates an array value.

The simplest form gives the length, the element type, and the elements:

const a = [4]i32{ 1, 2, 3, 4 };

This creates an array of four i32 values.

The number of elements must match the declared length. This is an error:

const a = [4]i32{ 1, 2, 3 };

The array says it has length 4, but only 3 elements are given.

When the compiler can count the elements itself, the length may be written as _:

const a = [_]u8{ 10, 20, 30, 40 };

The compiler determines that the type is:

[4]u8

This form is common because it avoids repeating the length.

Array literals may contain expressions:

const std = @import("std");

pub fn main() void {
    const x = 5;

    const a = [_]i32{
        x,
        x * 2,
        x * 3,
    };

    std.debug.print("{d}\n", .{a[2]});
}

The output is:

15

Trailing commas are allowed:

const a = [_]i32{
    1,
    2,
    3,
};

This style is preferred for multi-line literals because adding a new line changes only one line of text.

Array literals may be nested:

const std = @import("std");

pub fn main() void {
    const table = [2][3]i32{
        [3]i32{ 1, 2, 3 },
        [3]i32{ 4, 5, 6 },
    };

    std.debug.print("{d}\n", .{table[1][2]});
}

The output is:

6

The type [2][3]i32 means:

an array of 2 elements,
where each element is an array of 3 i32 values

Zig also allows repeated values with the repetition operator:

const a = [_]u8{0} ** 8;

This creates:

[8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }

This is useful for zero-filled buffers.

Another example:

const std = @import("std");

pub fn main() void {
    const stars = [_]u8{'*'} ** 5;

    for (stars) |c| {
        std.debug.print("{c}\n", .{c});
    }
}

The output is:

*
*
*
*
*

Array literals may initialize mutable arrays:

const std = @import("std");

pub fn main() void {
    var scores = [_]i32{ 10, 20, 30 };

    scores[1] = 99;

    std.debug.print("{d}\n", .{scores[1]});
}

The output is:

99

The literal creates the initial value. After initialization, the array behaves like any other array variable.

Character literals use single quotes:

const letters = [_]u8{ 'a', 'b', 'c' };

String literals use double quotes:

const word = "zig";

These are different. The first is an ordinary array literal. The second is a string literal with a sentinel terminator, discussed later.

Large literals are often easier to read when formatted vertically:

const primes = [_]u32{
    2,
    3,
    5,
    7,
    11,
    13,
    17,
    19,
};

This style makes changes simple and reduces mistakes in long tables.

Exercises.

Exercise 6-5. Declare an array literal containing the numbers 1 through 10 and print them with a for loop.

Exercise 6-6. Use [_] to let the compiler determine the array length.

Exercise 6-7. Create a 3×3 multiplication table with nested arrays.

Exercise 6-8. Create an array of 16 zero bytes using the repetition operator.