Skip to content

Variables and Scope

Chloë Strainge edited this page Oct 14, 2026 · 1 revision

Variables and scope

let declares or replaces a binding in the current scope. Assignment without let updates the nearest existing binding. A missing assignment destination is an error.

let $level = 1
{
    let $level = $level + 1
    echo $level
}
echo $level
{ $level = 3 }
echo $level
2
1
3

An initializer runs before its new binding is installed, so it can read the old binding. A failed initializer leaves the old binding intact. A fresh let can replace a previous annotation; assignment must respect the existing annotation.

Annotations and defaults

let $temperature: Float = 18
let $names: [String]
let $maybe: Integer | ()
echo $temperature $names.count $maybe
18.0 0 ()

Numbers default to zero, Boolean to false, String to empty text, and collections to empty collections. A type admitting () defaults to unit. Struct and enum bindings can be declared for later initialization, but cannot be read before a valid value is assigned. Unannotated variables accept later values of other types.

Destructuring and discard

let ($city, $temperature) = ["Reykjavik", 6]
let (_, $unit) = [123, "C"]
echo $city $temperature $unit
let _ = 2 + 2
Reykjavik 6 C

A pattern requires an array with exactly the same number of positions. _ discards a position; duplicate named bindings and nested patterns are rejected. let _ = expression consumes a result without creating a variable.

Caller scope and captures

Named functions resolve ordinary variables through active caller scopes within their module. An imported function uses its own module's variable environment. A caller can therefore supply a nearer binding of a name used by a named function. Anonymous functions instead capture live bindings where they are created. Closures explains retained local state.

pub controls module visibility. let export controls process inheritance. These are independent: see Modules and Environment.


Related: Functions and calls · Types

Clone this wiki locally