Init block to const-cast - does it copy?

Well, a sequel demands a little attention.

I moved my code from a harness, and out to global const space. I tweaked here and there to comptime everything. All good except this (break :init &c_ - well, the real code is different, but this is the critical equivalent). The compile error? “global variable contains reference to comptime var". This makes sense, except for the fact that all that moves on into runtime is a const, not an actual variable. Here is the reference explanation I found - @mlugg posted back in 2024, with his compiler update at the time. His prescription for “solving” the problem is to “copy first”:

pub const my_name: []const u8 = name: {
    var buf: [5]u8 = undefined;
    @memcpy(&buf, "mlugg");
    const final = buf; // if you don't do this, then you'll get the error
    break :name &final;
};

In our case, of course, we can just omit the ‘&’, which forces a copy (as discussed earlier in this thread, and verified on godbolt).

BUT - here’s the interesting thing… since this is now comptime domain, that copy is NOT a runtime copy, so godbolt tells me that, in this case, break :init c_ in a comptime block is “like” break :init &c_ in a runtime block, in that the assembly doesn’t contain the blob of mov lines. I may not be saying this right, but: “a comptime copy happens at comptime, so you won’t see any “copy” in the assembly code, which (only) indicates what will happen at runtime.”

In short, break :init &c_ will not work in a comptime block (er, with a var, in a block, which is global), and, furthermore, break :init c_, though it does a copy, does the copy at comptime, so you don’t wind up with copy stuffs in the binary, because there’s no runtime copying that has to happen. Interesting. Great. Please correct any details I’ve misinterpreted.

1 Like