Difference between let and var variables in Mojo with Example
Mojo is a programming language designed as a superset of Python, meaning it includes all the features and concepts of Python while also providing additional powerful features for systems programming.
Mojo is a programming language that builds upon Python, adding extra features for systems programming. If you're familiar with Python, you'll find Mojo easy to understand.
How to write a first program in Mojo?
Let's start with a simple example. In Mojo, you can write a "Hello World" program just like you would in Python:
print("Hello Mojo!")
What is the use of let and var in Mojo?
In Mojo, let
and var
are keywords used for variable declarations, but they have different characteristics:
-
let
declaration:- Variables declared with
let
are immutable, meaning their values cannot be changed once assigned. let
variables have block scope, which means they are only accessible within the block (e.g., function, loop, or conditional statement) in which they are declared.- If you try to reassign a value to a
let
variable, it will result in an error. let
variables are useful when you want to ensure that a value remains constant or immutable within a block.
- Variables declared with
-
var
declaration:- Variables declared with
var
are mutable, meaning their values can be changed after assignment. var
variables have function scope, which means they are accessible within the entire function in which they are declared.- You can reassign a value to a
var
variable without encountering an error. var
variables are useful when you need to modify the value of a variable throughout a function.
- Variables declared with
Here's an example to illustrate the difference:
def example_function():
let x = 5
var y = 10
if x == 5:
let x = 15
var y = 20
print("Inside if block: x =", x, "y =", y)
print("Outside if block: x =", x, "y =", y)
example_function()
In this example, we have a function called example_function
. Inside the function, we declare two variables, x
and y
, using let
and var
respectively.
Within the if block, we have a new let
variable x
with a value of 15, which shadows the outer x
variable with a value of 5. We also have a new var
variable y
with a value of 20, which shadows the outer y
variable with a value of 10. When we print the values inside the if block, we see the updated values.
Outside the if block, we print the values again, and we can observe that the let
variable x
retains its original value of 5, while the var
variable y
retains its updated value of 20.
When you run this program, it will output:
Inside if block: x = 15 y = 20
Outside if block: x = 5 y = 20
This example demonstrates how let
and var
declarations differ in terms of mutability and scope in Mojo.