What Is Type Casting In Mojo?

All the programming data comes in different forms, such as integers, floats, strings, Booleans, etc. But sometimes we need to convert one type of data into another to perform certain operations; this process is called type casting.

Type casting plays a vital role in Mojo for safe, fast, and error-free code.

What Is Type Casting?

Type casting means a type conversion process that converts a value from one data type to another.

Mojo is a strongly types language, so you can’t simply assign a float to an integer variable without explicitly converting it. This method ensures memory safety and predictable performance.

Simple Example of Type Casting:

fn main():
let age: Int = 25
let discount: Float32 = Float32(age) # Explicitly cast Int to Float32
print("Discount percent is:", discount)

Output:

Type casting in Mojo

Two Types of Type Casting In Mojo

Mojo programming language supports two types:

  • Explicit Type Casting (Also called manual)
  • Implicit Type Promotion

1) Explicit Type Casting

Using this type, we tell the compiler what conversion we want. In the example below, we convert an Integer into a Float:

let x: Int = 10
let y: Float64 = Float64(x) # Manual cast

This is the recommended and safest way to cast the values in Mojo programming.

2) Implicit Type Promotion

Mojo provides a powerful method to safely promote promotions with expressions, for example: adding an Int to a Float by internally promoting:

let a: Int = 5
let b: Float32 = 2.5
let result = a + b # `a` is promoted to Float32

We have promoted the values using this method, but this depends on compiler rules and is only allowed where it does not create memory issues.

Real-World Type Casting Example

Suppose, we create a temperature converter app:

fn main():
let temp_celsius: Float32 = 36.6
let temp_fahrenheit: Int = Int((temp_celsius * 9.0 / 5.0) + 32.0)

print("Body temperature in Fahrenheit:", temp_fahrenheit)

Output:

type casting in Mojo

First, see this code and understand how it will convert a Float value into an Int (rounded number).

How Much Type Cast Available In Mojo?

  • Integer-to-Integer Casting (Changing Bit Size)
  • Integer ↔ Float Casting
  • Float32 ↔ Float64 Casting
  • Optional Casting ( ? )
  • Boolean Casting (to Control Flow or Int)
  • String Conversions (Using Standard Library)

1) Integer-to-Integer Casting (Changing Bit Size)

We can cast between different integer sizes, such as Int8, Int16, Int 32, Int64, or the default Int.

fn main():
let small_num: Int8 = 100
let bigger_num: Int32 = Int32(small_num) # Safe widening cast
print("Casted Value:", bigger_num)

If you cast from small to big is safe, but if you cast big to small may cause overflow (data loss).

2) Integer ↔ Float Casting

We can also convert integers to float and float to integers. for Example:

fn main():
let points: Int = 95
let ratio: Float32 = Float32(points) / 100.0 # Int → Float

let pi: Float32 = 3.99
let rounded: Int = Int(pi) # Float → Int (result = 3)
print(ratio, rounded)

In this casting, Int to Float is safe, but Float to Int truncates the decimal part, so it’s important to handle carefully.

3) Float32 ↔ Float64 Casting

We can also switch between Float-32 and Float 64 in casting. For example:

fn main():
let num32: Float32 = 3.14
let num64: Float64 = Float64(num32)
print(num64)

This switch method mostly used in scientific or ML applications.

4) Optional Casting ( ? )

We learned this data type in previous topics. Mojo uses Optional types instead of null.

fn greet(name: String?):
if name != None:
let actual: String = name! # Cast from Optional to non-Optional
print("Hello,", actual)
else:
print("Hello, Guest!")

This is technically casting, because we are converting from string? (nullable) to String (non-null).

5) Boolean Casting (to Control Flow or Int)

We can convert Bool into Int manually for numeric operations like counters.

fn main():
let is_active: Bool = True
let as_number: Int = Int(is_active) # True → 1, False → 0
print(as_number)

See this example, Mojo doesn’t allow automatic True and False conversions like Python.

6) String Conversions (Using Standard Library)

Mojo doesn’t cast strings automatically, but we can convert numbers to strings for printing. and convert strings to numbers when parsing numbers.

# Pseudocode example (actual library functions vary)
let age_string: String = "25"
let age: Int = parseInt(age_string) # Converts String → Int

Beginner-Friendly Examples

Example 1: Average Marks to Grade (Float to Int)

fn main():
let total_marks: Float32 = 348.5
let subjects: Int = 5
let average: Int = Int(total_marks / Float32(subjects))

print("Average Score (rounded):", average)

Output:

type casting in Mojo

In this example, we learned how to handle float division and how to convert a float result into an integer for grading systems.

Example 2: Bill Calculation from User Points (Int to Float)

fn main():
let reward_points: Int = 120
let conversion_rate: Float32 = 0.75 # ₹0.75 per point
let rupees: Float32 = Float32(reward_points) * conversion_rate

print("Total reward value in ₹:", rupees)

Output:

Type casting in mojo

This app gives cashback based on points.

Avoid Mistakes In Type Casting

  • Don’t assign a Float to Int without casting.
  • Sometimes, Float to Int truncates decimal values.
  • Mojo is not Python. Be explicit unless you’re sure the compiler allows it.

Leave a Comment