Object-Oriented Programming in Mojo: How to Use Structs, Impls, and Methods

Mojo

Introduction

Mojo is gaining popularity not just for its performance and Python compatibility, but also for its clean approach to object-oriented programming (OOP). If you’re familiar with classes in Python or other languages, you’ll find Mojo’s OOP style both familiar and refreshingly structured. This article introduces how to work with objects in Mojo using struct, impl, constructors, and methods.

1. Understanding Structs in Mojo

In Mojo, the equivalent of a class is called a struct. Structs define the structure and data of an object, similar to data classes in Python or structs in Rust.

struct Person:
    var name: String
    var age: Int

This defines a simple Person struct with two properties: name and age.

2. Adding Behavior with impl Blocks

To define methods and logic associated with a struct, Mojo uses impl blocks. This is where you implement constructors, instance methods, and more.

impl Person:
    fn __init__(inout self, name: String, age: Int):
        self.name = name
        self.age = age

    fn greet(self):
        print("Hello, my name is", self.name)

The __init__ function acts as a constructor, and greet is a simple method. Note that inout self allows mutation during construction.

3. Creating and Using Objects

You can now create a Person object and call its methods just like in other object-oriented languages.

let p = Person("Alice", 30)
p.greet()  # Output: Hello, my name is Alice

4. Encapsulation and Readability

Mojo encourages clean encapsulation. You can separate logic into multiple impl blocks or even make read-only properties using let instead of var.

struct Book:
    let title: String
    var pages: Int

impl Book:
    fn summary(self):
        print("Book:", self.title, "-", self.pages, "pages")

5. Limitations and Best Practices

  • Currently, Mojo does not support full inheritance like traditional OOP languages.
  • Favor composition over inheritance where possible.
  • Use multiple impl blocks to organize complex logic.

Conclusion

Mojo’s object-oriented features are both minimalistic and powerful. By combining struct and impl, you can build clean, modular, and maintainable code structures. Whether you’re building a data model or adding behavior to your app, Mojo’s OOP system gives you a solid foundation. As the language evolves, expect even more features for scalable, object-based development.

Want to explore more? Check out our previous post: Mojo Basics: Variables, Data Types, and Operators

Comment

Copied title and URL