Comptime-field is a nonsense semantic?

The value of comptime fields can’t be modified (in compile time). And they don’t contribute to type sizes.

Is there any real usefulness of comptime fields?

const std = @import("std");

const T = struct {
    comptime n: u32 = 0,
    // <=>
    // const n: u32 = 0;
};

pub fn main() void {
    comptime var t: T = .{};
    //t.n = 1; // error:  value stored in comptime field does not match the default value of the field
    t = t;
    std.debug.print("{}\n", .{@sizeOf(T)}); // 0
}

Propagating comptimeness of values, comptime fields are most often used implicitly through anonymoust structs/tuples and anytype e.g print("{d}", .{1}).

it is also useful if you have a generic function that expects a field, but you dont want the runtime overhead.

comptime fields are effectively const that you access on an instance instead of the type/namespace.

4 Likes