Variables (v0.2.1)
Declaration and mutation patterns for local and static storage.
Overview
Local variables are declared with var. You can write the type yourself or use := when the compiler can infer it from the initializer.
Static declarations store values for the lifetime of the program. They can also be marked public or bound to external names when needed.
Keep mutable variables close to the code that uses them. This makes loops and branches easier to follow.
Primary source: syntax/variables/
Syntax Signatures
var counter: s32 = 0;
counter = counter + 1;
static mut depth: u16 @public @extern("depth") = 3;
Behavior and Use
Assignments change the current value of a variable. In longer functions, avoid spreading related assignments far apart.
Be careful with mutable static state. It is shared program state, so updates should happen through clear code paths.
Best Practices
- Prefer block-local variables over function-wide mutable state.
- Reset temporary state explicitly between loop iterations when needed.
- Keep static mutable variables behind dedicated API functions.
Local Declarations
Local variables live inside the block where they are declared.
- var name: Type = value declares a local with an explicit type.
- := asks the compiler to infer the type from the initializer. Use it when the initializer already makes the type obvious.
- A local declared in an inner block is not available after that block ends.
- Mutation is explicit through assignment and compound assignment operators. Keep related mutations close together.
Static Storage
Static declarations describe storage that exists for the lifetime of the program.
- static values are module-level storage. They are useful for exported symbols, shared state, and data that must have a stable address.
- static mut allows mutation of static storage. Treat it as shared state and keep writes in a small API.
- @public exports a static symbol. @extern binds it to an external symbol name.
Example
fn main() s32 @public {
var i: s32 = 0;
var total: s32 = 0;
while i < 10 {
total += i;
i++;
}
return total;
}