Skip to content

Comptime fields

Chung Leong edited this page Apr 24, 2024 · 3 revisions

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});
}
import { main } from './comptime-field-example-1.zig';

main();
Size: 16
comptime-field-example-1.Header{ .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 JavaScript side:

import { Header } from './comptime-field-example-1.zig';

const header = new Header({ id: 123, flags: 0, offset:0 });
console.log(header.valueOf())
{ size: 16, id: 123, flags: 0, offset: 0n }

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,
};
import { DataSection } from './comptime-field-example-2.zig';

const section = new DataSection({ offset: 16n, len: 256n });
console.log(section.valueOf());
{ type: 'data', offset: 16n, len: 256n }
Clone this wiki locally