Skip to content
Chung Leong edited this page Feb 12, 2024 · 12 revisions

In Zig, arrays can contain only a single type of values. Their lengths are fixed at compile time.

const std = @import("std");

pub fn print4(values: [4]i32) void {
    std.debug.print("{d}\n", .{values});
}
import { print4 } from './array-example-1.zig';

print4([ 123, 234, 345, 456 ]);
{ 123, 234, 345, 456 }

Array objects support bracket operator and iterator.

pub fn get4(offset: i32) [4]i32 {
    var values: [4]i32 = undefined;
    for (&values, 0..) |*value_ptr, index| {
        value_ptr.* = @as(i32, @intCast(index)) + offset;
    }
    return values;
}
import { get4 } from './array-example-2.zig';

const array = get4(80);
console.log(array[3]);
for (const value of array) {
    console.log(value);
}
console.log([ ...array ]);
83
80
81
82
83
80, 81, 82, 83

Array objects also provide get and set methods. Accessing an array through them is more performant than using the [] operator.

import { get4 } from './array-example-2.zig';

const array = get4(80);
for (const { get, set, length } = array, i = 0; i < length; i++) {
    console.log(get(i));
    set(i, i + 101);
}
console.log([ ...array ]);
80
81
82
83
101, 102, 103, 104

u8 and u16 arrays have the special property string, which interprets an array's content as UTF-8/16 encoded text.

const std = @import("std");

const hello: [12]u8 = "Привіт";

pub fn getHello8() [hello.length]u8 {
    return hello;
}

pub fn getHello16() [hello.length / 2]u16 {
    var codepoints: [hello.length / 2]u16 = undefined;
    var view = std.unicode.initUnchecked(&hello);
    var iterator = view.iterator();
    for (codepoints) |*codepoint_ptr| {
        codepoint_ptr.* = @truncate(iterator.nextCodepoint());
    }
    return codepoints;
}
import { getHello8, getHello16 } from './array-example-3.zig';

console.log(getHello8().string);
console.log(getHello16().string);
Привіт
Привіт

Arrays of integers and floats will also have the special property typedArray, which yields one of JavaScript's typed arrays.

pub fn get4Big(offset: i64) [4]i64 {
    var values: [4]i64 = undefined;
    for (values, 0..) |*value_ptr, index| {
        value_ptr.* = offset + index;
    }
    return values;
} 
import { get4Big } from './array-example-4.zig';

const { typedArray } = get4Big(50);
console.log(typedArray instanceof BigInt64Array);
Clone this wiki locally