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;
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.