Variables (v0.2.1)

Declaration and mutation patterns for local and static storage.

Latest

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

Local Declarations

Local variables live inside the block where they are declared.

Static Storage

Static declarations describe storage that exists for the lifetime of the program.

Example

fn main() s32 @public {
    var i: s32 = 0;
    var total: s32 = 0;

    while i < 10 {
        total += i;
        i++;
    }

    return total;
}

Back to language reference