Comptime fields ᴾᴴᴾ - chung-leong/zigar GitHub Wiki

JavaScript | PHP


In the Zig language, a comptime field is basically a constant masquerading as a struct field:

const std = @import("std");

pub const Header = struct {
    comptime size: u32 = @sizeOf(@This()),
    id: u32,
    flags: u32,
    offset: u64,
};

pub fn main() void {
    var header: Header = undefined;
    header.id = 123;
    header.flags = 0xFF;
    header.offset = 0x1000000;
    std.debug.print("Size: {d}\n", .{header.size});
    std.debug.print("{any}\n", .{header});
}
<?php

$m = zigar_use(__DIR__ . '/comptime-field-example-1.zig');

$m->main();
Size: 16
.{ .size = 16, .id = 123, .flags = 255, .offset = 16777216 }

In the above example, only id, flags, and offset are actually in the struct. size is not a real field. We can access it as though it is, however. And it appears as a field when we print it using std.debug.print(). The same thing happens on the PHP side:

<?php

$m = zigar_use(__DIR__ . '/comptime-field-example-1.zig');

$header = new $m->Header(id: 123, flags: 0, offset: 0);
print_r($header);
Header Object
(
    [size] => 16
    [id] => 123
    [flags] => 0
    [offset] => 0
)

Comptime-only values like types and enum literals can be stored in comptime fields:

pub const DataSection = struct {
    comptime type: @TypeOf(.enum_literal) = .data,
    offset: i64,
    len: i64,
};
<?php

$m = zigar_use(__DIR__ . '/comptime-field-example-2.zig');

$section = new $m->DataSection(offset: 16, len: 256);
print_r($section);
DataSection Object
(
    [type] => data
    [offset] => 16
    [len] => 256
)