How to construct a tuple at compile time using a for loop?

I’ll share a little secret with you… here’s a dirty trick for weakly-typed comptime:

comptime {
    const init_val = .{};
    var cur_ptr: *const anyopaque = &init_val;
    var CurTy = @TypeOf(init_val);
    for (.{ 92, "walrus", false }) |item| {
        const cur_val = @as(*const CurTy, @alignCast(@ptrCast(cur_ptr))).*;
        const new_val = cur_val ++ .{item};
        cur_ptr = &new_val;
        CurTy = @TypeOf(new_val);
    }
    const final = @as(*const CurTy, @alignCast(@ptrCast(cur_ptr))).*;
    @compileLog(final);
}

Note that the init_val is necessary due to a minor compiler bug which writing const ptr: *const anyopaque = &.{} exposes (although perhaps it’s good for that to not work…).

6 Likes