Variables & Mutability

Note: As of v24.1, the let keyword has been retired. All runtime local variables must now use the var keyword.

Mojo manages mutability through two primary keywords: var for mutable runtime values, and alias for immutable compile-time values.

1. Mutable Variables (var)

var creates a mutable binding. The value and the memory it points to can be changed after the initial assignment.

fn main():
    var count: Int = 0      # Mutable — value can change
    count = count + 1
    print(count)

    var name = "Mojo"
    name = "Python"        # OK: var allows reassignment
    print(name)

2. Compile-Time Constants (alias)

For true immutability, Mojo uses alias. An alias is a value known at compile-time. It cannot be reassigned, and because the compiler knows its value upfront, it offers the highest level of optimization.

fn main():
    alias MAX_CONNECTIONS = 100
    # MAX_CONNECTIONS = 200   # ERROR: alias is immutable
    print(MAX_CONNECTIONS)

The "Borrowing" Alternative

While local variables use var, remember that function arguments are immutable by default. They are "borrowed" references, meaning you cannot modify them unless you explicitly mark them as inout.

Constraint

Write a script that defines an alias for a mathematical constant (like PI) and a var for a radius. Calculate the area and try to reassign both to see which one the compiler protects.

Why It Matters

Using alias whenever possible allows the Mojo compiler to perform "constant folding," replacing calculations with their results before the program even runs. Use var for data that evolves during execution.