Skip to main content

Variables And Mutability

·232 words·2 mins
Documentation - This article is part of a series.
Part 4: This Article

Let Bindings
#

Variables are bound in Sage using the let keyword. You can optionally include the type of the variable to be typechecked against.

// Create a variable named a, with the value 5
let a = 5;
let b = {x=5, y=6};
let c: (Int, Int, Int) = (1, 2, 3); // Optionally include the type

println(a);
println(b);
println(c);
Output:
5
{x=5, y=6}
(1, 2, 3)

Mutability
#

You can make a variable as mutable with the mut keyword. If you try to assign to a variable that isn’t mutable, the compiler will yell at you!

let mut a = 5;
println(a);
a = 6;
println(a);
Output:
5
6

Destructured Let Bindings
#

In many instances, users want to be able to decompose the attributes of structures or tuples into variables.

let (a, {mut x, y}) = (1, {x=5, y=6});
println(a, ", ", x, ", ", y);
x = 999;
println(a, ", ", x, ", ", y);
Output:
1, 5, 6
1, 999, 6

Variables And Scope
#

Variables are not captured by functions – functions mainly act as procedures. Additionally, variables may not be referenced before their definition.

println(a);
let a = 5;
Error:
2 │ println(a);
LIR error: symbol a not defined

Scopes may also be created with {} blocks.

{
    let a = 5;
    println(a);
}
println(a);
Error:
5 │ println(a);
LIR error: symbol a not defined
Documentation - This article is part of a series.
Part 4: This Article