In Mojo, variables are simply names you give to store values or objects. Think of them as labels on jars, where each jar can hold something different. These variables are mutable, meaning you can change what's inside the jar after you've put something in it.
Constants vs. Variables
- Constants: To have a jar that never changes its content, use the
alias
keyword. It's like sealing the jar forever.
- Variables: If you're okay with changing the content, just use a variable.
Quick Note on Immutability
- Mojo used to have
let
for creating unchangeable variables. Now, let
is just like var
, but it's there to help people with old code switch to the new way without hassle.
Types of Variables
- Undeclared Variables: You can make a variable on the fly inside a
def
function or when playing around in the Mojo interactive environment (REPL). Just give it a name and a value, like name = "Sam"
. But, these casual variables are a no-go inside fn
functions or as part of a structure's blueprint.
- Declared Variables: Use
var
when you want to formally declare a variable. It's like saying, "I'm going to use this jar for something specific." You can specify what type of thing the jar will hold, like an integer with var user_id: Int
, or you can fill it immediately with something, like var name = "Sam"
.
Rules for Declared Variables
- Types Matter: Once you tell Mojo what type of thing a jar holds, you can't sneak in something else. If you say a jar is for integers, you can't put a string in it.
- Typos: Mojo is like a careful librarian with declared variables. If you misspell a variable name, Mojo will let you know instead of just creating a new jar with the misspelled label.
- Scope: Variables declared with
var
live within specific boundaries. They know where they belong, and they can't just wander off into another section of your code.
Going Deeper with Types
- Type Annotations: You can be super clear about what goes in your jar by adding a type annotation, like
var name: String = "Sam"
. This makes your code cleaner and safer because Mojo makes sure you stick to the rules.
- Late Initialization: Sometimes, you might want to declare a jar but decide what to put in it later. Type annotations let you do that. Just be sure to fill the jar before you try to use what's inside.
- Implicit Type Conversion: Mojo is smart enough to convert things for you in certain cases, like turning the number 1 into the string "1" if you need it to be a string.
Understanding Variable Scopes
- Lexical Scoping for Declared Variables: Variables know their place. If you create a variable inside a block of code, it stays there. It's like having a jar that only exists within a specific room.
- Function-Level Scoping for Undeclared Variables: Undeclared variables are more free-spirited. They roam around the entire function where they're created. Change them in one place, and you've changed them everywhere in that function.