Variables
Variables can have any name which does not start with a number. Variables are mutable, and always passed by value to functions.
Declaration
Variables need to be declared to be used. Declaration and definition are always combined, so that undefined variables do not exist.
def main() {
// declare and define `my_variable`
field mut my_variable = 2;
// redefine `my_variable`
my_variable = 3;
return;
}
Mutability
Variables are immutable by default. In order to declare a mutable variable, the mut
keyword is used.
def main() {
field a = 42;
// a = 43; <- not allowed, as `a` is immutable
field mut b = 42;
b = 43; // ok
return;
}
Shadowing
Shadowing is allowed.
def main() -> field {
field a = 2;
field a = 3; // shadowing
for u32 i in 0..5 {
bool a = true; // shadowing
}
// `a` is the variable declared before the loop
return a;
}
Scope
Function
Functions have their own scope
def foo() -> field {
// return myGlobal; <- not allowed
return 42;
}
def main() -> field {
field myGlobal = 42;
return foo();
}
For-loop
For-loops have their own scope
def main() -> u32 {
u32 mut a = 0;
for u32 i in 0..5 {
a = a + i;
}
// return i; <- not allowed
return a;
}