comptime functions
When the same pre-computation logic needs to be called in multiple places, an
inline block becomes repetitive. The solution is to declare a comptime
function: annotate the function with @comptime and it can then be invoked
with comptime f(args) in any expression. Each call is resolved by the
compiler and replaced by the corresponding literal.
Unlike a standalone block, the function has a name, accepts typed parameters,
and can be composed — you can add comptime double(10) and comptime triple(4) in the same expression and the compiler resolves both before
generating code.
Two @comptime functions combined in the same expression — the result is a single literal.
// Feature: comptime <expr> — call a `@comptime fn` and bake the result
// Syntax: declare with `@comptime fn`; invoke with `comptime f(x)`.
// The function runs in the compiler and the call site is replaced
// with the literal result.
// When to use: short, pure helpers — math, string formatting, table
// lookups — that you want resolved before runtime.
@comptime
fn double(n: int) -> int {
return n * 2
}
let x = comptime double(21)
print(x)
// expected: 42
// Multiple comptime calls in one expression.
@comptime
fn triple(n: int) -> int {
return n * 3
}
let y = comptime double(10) + comptime triple(4)
print(y)
// expected: 32
A practical note: the unused-function lint may flag a @comptime fn as "never
called", since comptime invocations do not appear as runtime calls. It is safe
to ignore that warning.