I need ideally a (global) const to be var depending on a comptime boolean.
Is that possible in 1 declaration?
pub const we_can_change: bool = false;
pub const value: i32 = 42; // if we_can_change is false
pub var value: i32 = 42; // if we_can_change is true
Fitti
July 18, 2026, 3:58pm
2
The one way I can think of right now would be something like
const std = @import("std");
// Compile error, "cannot assign to constant"
// const we_can_change = false;
// Runs just fine!
const we_can_change = true;
pub const wrapper = if (we_can_change) struct {
pub var value: i32 = 42;
} else struct {
pub const value: i32 = 42;
};
// Skipping the wrapper by using a pointer
// is another option
// pub const value = &wrapper.value;
pub fn main() !void {
wrapper.value = 12;
std.debug.print("{d}\n", .{wrapper.value});
}
Edit: This of course also works if you define wrapper inside main instead, though that would probably defeat the purpose.
Edit 2: A more direct way to go the pointer route, the sacrifice being a second declaration:
var backing: i32 = 42;
pub const value: if (we_can_change) *i32 else *const i32 = &backing;
3 Likes
good ideas. fooling around with it now.
But if we go the pointer way, we need allocations right?
Edit: in my case it is more complicated. mutable type = 4 fields in a struct, unmutable type is a hard constant.
pasta
July 18, 2026, 5:44pm
4
@Fitti ’s code works verbatim, you can point to global memory .
1 Like