I don’t think it is actually. Comptime mutable values aren’t supposed to escape from their scope, so your fix takes a comptime-variable value, makes it const so that it can be returned, and this is then assigned to a global var, meaning it’s mutable again, but not until runtime.
The rules are a bit confusing and underdocumented, but I think that’s how it’s supposed to work.
Speaking of which @sanomigton, unless you intend to mutate the field names at runtime, you’re better off using const for that variable. Welcome to Ziggit btw.
But there are other cases where you actually get a compiler error and the code has the analysis of how the values escape their scope, I can’t imagine this is just supposed to crash the compiler. I think this is just a case where that is bugged, maybe it is already fixed in newer versions, otherwise it should become part of an issue and looked at in more detail.
No but there’s two kind of “that’s a bug” possible here: the kind where the program shouldn’t compile but the compiler also shouldn’t crash, and the kind where it should compile and the compiler crashes anyway.
I was thinking this was the first kind of program, and upon rethinking it, I’m inclined to say that it’s the second. The coercion to constant in the return type should have taken care of the “mutability cannot escape” part.
It looks like this has been recently fixed in nightly zig. I was able to reproduce the crash with 0.14.0-dev.1730+034577555. But now the compiler catches it. I suspect https://github.com/ziglang/zig/pull/21618 fixed it.
$ zig version
0.14.0-dev.1860+2e2927735
$ zig run /tmp/tmp.zig
/tmp/tmp.zig:3:44: error: global variable contains reference to comptime var
var person_field_names = generateFieldNames(Person);
~~~~~~~~~~~~~~~~~~^~~~~~~~
referenced by:
main: /tmp/tmp.zig:31:10
posixCallMainAndExit: ~/zig/zig/download/0.14.0-dev.1860+2e2927735/files/lib/std/start.zig:612:22
4 reference(s) hidden; use '-freference-trace=6' to see all references
Thanks for the clarification! That makes sense—the nuances around comptime mutability and how it transitions to runtime can definitely be tricky. I appreciate you pointing that out.
I’ll update the variable to be const since I’m not planning to mutate the field names at runtime, as you suggested. Also, thanks for the warm welcome to Ziggit! Still getting used to some of the subtleties, but it’s exciting to learn.