Hands On Mojo Traits 1

Created: 11 February 2025  Modified: 11 February 2025

Understanding Mojo traits (struct) is critical to being able to read Mojo Standard Library documentation. We will try to keep our exploration of traits 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.

This article entry is based on Hands On Mojo Structures.

Mojo traits are roughly analogous to Java interfaces. They are a blueprint that a method or a function can use as a contract. Unlike Java interfaces, traits can be defined and will match already existing structures.

For our first code example we will use the already existing Writable trait. In the below code we add the “write_to” method as defined by the documentaton (link above). This allows us to reduce the number of print statments needed.

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

    fn write_to[W: Writer](self, mut writer: W):
        writer.write(self.name, " ", self.eyeColor, " ", self.heightInches)

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