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.

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

const array = get4(80);
const { get, set, length } = array;
for (let i = 0; i < length; i++) {
    console.log(get(i));
    set(i, i + 101);
}
console.log([ ...array ]);
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 = "Привіт";

pub fn getHello8() [hello.len]u8 {
    var bytes: [hello.len]u8 = undefined;
    for (&bytes, 0..) |*byte_ptr, index| {
        byte_ptr.* = hello[index];
    }
    return bytes;
}

pub fn getHello16() [hello.len / 2]u16 {
    var codepoints: [hello.len / 2]u16 = undefined;
    var view = std.unicode.Utf8View.initUnchecked(hello);
    var iterator = view.iterator();
    for (&codepoints) |*codepoint_ptr| {
        if (iterator.nextCodepoint()) |cp| {
            codepoint_ptr.* = @truncate(cp);
        }
    }
    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.* = @as(i64, @intCast(index)) + offset;
    }
    return values;
}
import { get4Big } from './array-example-4.zig';

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