Constants (v0.2.1)
Compile-time values that cannot be reassigned.
Overview
Constants define values known at compile time. They are useful for sizes, flags, protocol values, and other numbers that should not be repeated throughout the code.
Constants can be built from compile-time helpers such as sizeOf and alignOf. That keeps layout-related values tied to the type they describe.
Use constants when the value is part of the program definition, not something that changes at runtime.
Primary source: syntax/constants/
Syntax Signatures
const U32_SIZE: usize = sizeOf(u32);
const F64_ALIGN: u32 = alignOf(f64);
const READY: bool = true;
Behavior and Use
A constant cannot be reassigned. The compiler can use the value directly wherever the constant is referenced.
Keep constants near the code or module they describe. Very large global constant files are harder to maintain.
Best Practices
- Define capacities once and reuse them across modules.
- Use constants to derive array sizes and static checks.
- Name constants after what they mean, not just after their type.
Compile-Time Values
Constants are resolved while the program is compiled.
- const name: Type = value declares a value that cannot be reassigned.
- A constant expression can include literals and compile-time builtins such as sizeOf, alignOf, and pointerWidth.
- Use constants for protocol values, flags, array sizes, ABI checks, and limits that are part of the program definition.
Constants Versus Variables
Use constants when the value is a rule, not state.
- A variable stores runtime state and can change as the function executes.
- A constant documents a fixed decision and lets the compiler reuse that value directly.
- If a value depends on input, file contents, allocation, or an external call, it belongs in runtime code instead of a const declaration.
Example
const BUFFER_CAPACITY: usize = 1024;
fn capacity() usize @public {
return BUFFER_CAPACITY;
}