Version: 1.1.0
Variables
A Mojo variable is introduced with var. The name is fixed to one type for its whole lifetime.
Essentials
- Write
var score = 0and Mojo infersInt. - Write
var score: Intwhen you need the name before it has a value, then initialize it on every path. - Assignment updates the value. It does not change the type.
- Names that start with an underscore are treated as private by convention.
Example
def main():
var total: Int = 0
for i in range(10):
total += i
print(total)
Keep in mind
If a name is used before it is initialized on every path, compilation fails. That check is what keeps late bugs out of runtime.