Type Annotations and Static Typing in Mojo

Mojo

Mojo is built with performance in mind, and one of its key design choices is embracing static typing. If you come from Python, where types are optional (and often avoided), Mojo’s approach might feel strict at first — but stick with it. In this article, we’ll take a look at how type annotations work in Mojo, why they matter, and how they help you write safer and faster code.

Why Static Typing?

Static typing means the type of every variable is known at compile time. This gives the Mojo compiler more room to optimize your code, and it helps catch bugs early. Unlike Python, where you can accidentally pass a string to a function expecting an integer, Mojo will let you know up front.

Basic Type Annotations

Here’s how you define a variable or a function with explicit types in Mojo:

var age: Int = 30

fn greet(name: String) -> String:
    return "Hello, " + name

Simple, right? Just use a colon to specify the type, and Mojo does the rest. The return type of a function comes after ->.

Common Types in Mojo

Some of the basic types you’ll see often include:

  • Int – whole numbers
  • Float – decimal numbers
  • String – text
  • Bool – true or false

You can also work with lists, tuples, and more complex types — though support is still growing as Mojo evolves.

Type Checking at Compile Time

What makes Mojo really shine is that it doesn’t just annotate types — it actually enforces them. If you try this:

fn square(x: Int) -> Int:
    return x * x

square("hello")  # ❌ This will cause a compile-time error

The compiler will stop you right there. This might feel limiting at first, but in the long run, it saves you from weird runtime crashes.

Optional Type Inference

You don’t always need to annotate everything. Mojo can often infer the type based on the value:

var x = 42     # Inferred as Int
var name = "Mojo"  # Inferred as String

But for function signatures and more complex logic, explicit types are strongly encouraged.

Conclusion

Getting used to static typing might take a bit of adjustment if you come from Python, but it’s a shift that pays off. Mojo’s type system not only boosts performance, but also makes your code more predictable, readable, and safe. Once you start leaning into types, you’ll wonder how you ever coded without them.

Comment

Copied title and URL