What Are Constants In Mojo?

In Mojo programming, constants are useful when we want to define fixed values that cannot be changed after being declared.

This method is useful when you want to protect specific values from being accidentally modified in your program.

In simple terms, A constant is a value that is assigned once and does not change during the program’s execution. Mojo uses the let keyword to define constants.

It’s different from a variable, which can be updated or reassigned.

Syntax of Declaring Constants in Mojo

let constant_name: Type = value

Explanation of this syntax:

  • let keyword is used to declare a constant.
  • constant_name is the name of the constant
  • Type represents the data type, such as Int32, Float64, Bool, etc.
  • value represents a fixed value assigned.

Why Use Constants in Mojo?

1) Constants make our code more secure and avoid accidental changes.

2) It’s more readable because it explains fixed values

3) A constant is easier to maintain in a single place to update important values.

4) Prevents logic bugs in values and makes our functions error-free.

Real-Life Examples Using Mojo Constants

Now, you can learn some practical and beginner-friendly examples that show how constants work in real-world scenarios.

Example 1: Area of a Circle

Let’s calculate the area using the constant value.

fn main():
let PI: Float64 = 3.14159
let radius: Float64 = 5.0
let area: Float64 = PI * radius * radius

print("Area of the circle is:", area)

Output:

Area of the circle is: 78.53975

You can see that PI is declared as a constant, and the value of π remains unchanged.

Example 2: Maximum Login Attempts (Security Example)

fn main():
let MAX_ATTEMPTS: Int32 = 3
var attempts: Int32 = 0

while attempts < MAX_ATTEMPTS:
print("Attempt number:", attempts + 1)
attempts += 1

print("Too many failed attempts. Account locked.")

Output:

Attempt number: 1
Attempt number: 2
Attempt number: 3
Too many failed attempts. Account locked.

MAX_ATTEMPTS is a constant that improves code security and clarity.

Important Rules for Mojo Constants

  • Must be initialized at declaration.
  • Type must be known at compile time.
  • Cannot be reassigned or changed.
  • Use the let keyword instead of var.

Now, see what happens if you try to change a Constant?

fn main():
let site_name: String = "BoxOfLearn"
site_name = "MojoWorld" # Error: Cannot assign to constant

Mojo will throw a compile-time error. Constants are immutable by default.

Exercise For Learners

Exercise 1: Train Ticket Price Calculator (Using Constant)

Use a constant fare per kilometer and calculate the total price of a train ticket based on user input (distance in kilometers).

Requirements:

  • Declare a const for fare per kilometer (For example: const FARE_PER_KM = 2.5)
  • Take distance as a variable (120 km)
  • Multiply to get total fare
  • Print final ticket price

Your final output will look like this:

Train distance: 120 km
Fare per km: ₹2.5
Total ticket price: ₹300.0

Code Program of this exercise:

const FARE_PER_KM: Float64 = 2.5  # Constant fare rate per kilometer

fn main():
# Input distance of the journey in kilometers
let distance_km: Int = 120

# Calculate total fare
let total_fare: Float64 = distance_km * FARE_PER_KM

# Print the results
print("Train distance: ", distance_km, " km")
print("Fare per km: ₹", FARE_PER_KM)
print("Total ticket price: ₹", total_fare)

Learn this code by yourself and try to understand each block of code that we have written in the program.

Exercise 2: Classroom Max Capacity Checker

Use a constant to define the maximum number of students allowed in a classroom, and check whether new admission is allowed or not.

  • Declare a const MAX_STUDENTS = 30
  • Take current number of students as variable (e.g., 28)
  • Calculate remaining seats and print result
  • If full the spaces, then print “Admission closed” message.

Your final output will look like:

Current students: 28
Maximum allowed: 30
Seats remaining: 2
Admission status: Open

Also Learn this Topics:

Leave a Comment