Variables
Variables store values that can be used throughout a program.
Declaring Variables
Variables are declared using the var keyword.
Variables are immutable by default. To allow reassignment, use the mut modifier.
A variable declaration consists of:
- the
varkeyword, - an optional
mutmodifier, - the variable name,
- an optional type annotation,
- an initializer.
Every variable declaration must provide an initializer.
Type Inference
When an initializer is present, the compiler automatically infers the variable's type.
The examples above are inferred as:
Type inference is performed entirely at compile time.
Explicit Types
A variable's type may be specified explicitly using :.
Explicit type annotations are optional whenever the type can be inferred.
Mutability
Variables declared with var cannot be modified after initialization.
To allow reassignment, declare the variable with var mut.
Mutability is explicit to make accidental modification less likely.
Assignment
Only mutable variables may be assigned new values.
Assignments must be compatible with the variable's type.
Assigning a value of an incompatible type results in a compile-time error.
Variable Scope
Variables are visible only within the scope in which they are declared.
importc "stdio"
fn main: int do
if true then
var message = "Hello"
printf("%s\n", message)
end
return 0
end
Variables declared inside a block are not accessible outside that block.
Inner scopes may shadow variables declared in outer scopes.
Global Variables
Variables may be declared outside of functions.
Global variables are accessible throughout the program.
Examples
A variable with an inferred type.
A mutable variable.
A variable with an explicit type.
A global variable.