zig
zig copied to clipboard
PROPOSAL: introduce a `final` keyword to differenciate between comptime constants and runtime "constants"
Problems With The Current Behavior
Zig code mix comptime and runtime constructs but it's often hard to distinguish between them but with zig's emphasis on comptime constructs and manipulation it, I think, a necessity to ease this process.
const N = @import(...);
const T = @import(...).T;
const c1 = magicNumber();
var a: u8 = 120;
pub fn main() void {
const b = getCurrentTime(); // ???
const c2 = buildNo(); // ???
N.doStuff(b);
N.doStuff(c2);
...
}
The final
Proposal
const N = @import(...); // a namespace
const T = @import(...).T; // a type
const b = magicNumber(); // 'static' constant (comptime known)
var a: u8 = 120; // 'static' variable
pub fn main() void {
final b1 = getCurrentTime();
const b2 = buildNo(); // 'static' constant (comptime known)
N.doStuff(b2);
N.doStuff(b1);
...
}
- All comptime known/only constructs should use
const
orcomptime var
and runtime known/only ones usevar
orfinal
- Mixed expressions result are resolved accordingly
- comptime and comptime = comptime =>
const
orcomptime var
- comptime and runtime = runtime =>
var
orfinal
- runtime and runtime = runtime =>
var
orfinal
- comptime and comptime = comptime =>
- Container level declarations cannot be
final
-
const
also always means 'static'
fn foo(i: u32) void {
const n = 1234;
doStuff(n, i);
}
will always be like doing
const n = 1234;
fn foo(i: u32) void {
doStuff(n, i);
}
- Runtime constants cannot be
final
-
const c = expr;
<=>const c = comptime expr;
-
final b = comptime expr;
will be illegal -
var a = comptime expr;
remains legal
-