Hands On Mojo Structures

Created: 10 February 2025  Modified: 10 February 2025

Understanding Mojo structures (struct) is critical to being able to read Mojo Standard Library documentation. We will try to keep our exploration of structs as shallow as possible so we can jump right in to writing compilable code. The goal is to provide enough understanding of Mojo structures to enable reading of documentation.

If you need help installing Mojo you can watch our Mojo Lang Install video.

Mojo structs are loosely analogous to Java classes. The main difference being they do not support inheritance. Mojo Structs Class Comparison. We are going to focus only on struct basic ability to hold data.

All values in Mojo have an associated data type. Most of the types are nominal types, defined by a struct. These types are nominal (or “named”) because type equality is determined by the type’s name, not its structure. Mojo Manual

For day to day use you can think of all data types in Mojo as structures. Boolean, String and numeric types are all structures. Boolean and numeric types are aliases of the DType struct.

Before we begin read and writing example code we need to briefly discuss Mojo Decorators. A decorator is code that executes during compilation of the code. The @value decorator we use below adds all the necessary boiler plate methods a struct needs for compilation.

1
2
3
4
5
6
7
8
9
10
11
12
@value
struct Person:
    var name: String
    var eyeColor: String
    var heightInches: Float16

fn main():
    bob = Person("Bob", "Brown", 70.5)
    bob.name = "Ralph"
    print(bob.name)
    print(bob.eyeColor)
    print(bob.heightInches)
tags: mojo - mojolang - structure - structures
   Improve every day.