Skip to content

Mojo Traits

A trait is a list of methods that a type promises to have. Once a struct says “I conform to Shape”, the compiler checks that it really has every method Shape asks for. In return, you can write one function that works with any shape, whether it’s a square, a circle or a type someone writes next year. You’ve been using traits already: Writable, Comparable and Sized are traits from the standard library. This lesson shows how to write your own.

A trait looks like a struct with method signatures but no real bodies:

trait Shape:
def area(self) -> Float64:
...

The ... (three dots) means “required”: the trait doesn’t say how to compute the area, only that every shape must be able to. A trait has no fields and you can’t create a value of it; it’s a contract, not a type you fill with data.

A struct conforms to a trait by listing it in parentheses and writing the required methods:

trait Shape:
def area(self) -> Float64:
...
@fieldwise_init
struct Square(Shape):
var side: Float64
def area(self) -> Float64:
return self.side * self.side
@fieldwise_init
struct Circle(Shape):
var radius: Float64
def area(self) -> Float64:
return 3.14159 * self.radius * self.radius
def main():
print(Square(3.0).area())
print(Circle(1.0).area())

Output:

9.0
3.14159

So far this looks like two structs that happen to have the same method. The trait starts to pay off in two ways: the compiler checks every conforming struct, and you can write code that accepts any of them.

If a struct claims a trait but forgets a method, it doesn’t build:

trait Shape:
def area(self) -> Float64:
...
@fieldwise_init
struct Square(Shape):
var side: Float64
def main():
var s = Square(2.0)
print(s.side)
hello.mojo:6:8: error: 'Square' does not implement all requirements for 'Shape'
struct Square(Shape):
^
hello.mojo:2:9: note: required function 'area' is not implemented
def area(self) -> Float64:
^
hello.mojo:1:7: note: trait 'Shape' declared here
trait Shape:
^
mojo: error: failed to parse the provided Mojo source module

The error names the trait and the missing method. Traits are all or nothing: a struct either has everything the trait asks for, or it doesn’t conform.

Here’s the main reason traits exist. Write the argument type as Some[Shape] and the function accepts any type that conforms to Shape:

trait Shape:
def area(self) -> Float64:
...
@fieldwise_init
struct Square(Shape):
var side: Float64
def area(self) -> Float64:
return self.side * self.side
@fieldwise_init
struct Circle(Shape):
var radius: Float64
def area(self) -> Float64:
return 3.14159 * self.radius * self.radius
def report(s: Some[Shape]):
print("area:", s.area())
def main():
report(Square(3.0))
report(Circle(2.0))

Output:

area: 9.0
area: 12.56636

Inside report, the only thing Mojo knows about s is that it’s some shape, so you can call s.area() and nothing else. At compile time, Mojo makes a version of report for Square and another for Circle. That’s why traits cost nothing at runtime: there’s no lookup while the program runs.

In Python, “duck typing” means that if an object has an area method, you can treat it as a shape. Mojo doesn’t work that way. A struct with the right method but no (Shape) doesn’t count:

trait Shape:
def area(self) -> Float64:
...
@fieldwise_init
struct Square:
var side: Float64
def area(self) -> Float64:
return self.side * self.side
def report(s: Some[Shape]):
print("area:", s.area())
def main():
report(Square(2.0))
hello.mojo:16:18: error: invalid call to 'report': value passed to 's' cannot be converted from 'Square' to 'T', argument type 'Square' does not conform to trait 'Shape'
report(Square(2.0))
~~~~~~ ~~~~~~^~~~~
hello.mojo:12:5: note: function declared here
def report(s: Some[Shape]):
^
mojo: error: failed to parse the provided Mojo source module

This is on purpose. Saying (Shape) is a statement that your area means what the trait means, and it lets the compiler catch a missing or misspelled method right where the struct is defined.

Some[Shape] is a shortcut. The longer form gives the type a name in square brackets. You need it when two arguments must be the same shape type:

trait Shape:
def area(self) -> Float64:
...
@fieldwise_init
struct Square(Shape):
var side: Float64
def area(self) -> Float64:
return self.side * self.side
def total_area[T: Shape](a: T, b: T) -> Float64:
return a.area() + b.area()
def main():
print(total_area(Square(2.0), Square(3.0)))

Output:

13.0

Read [T: Shape] as “for some type T that conforms to Shape”. Both a and b are T, so total_area(Square(2.0), Circle(1.0)) would fail with “cannot be converted from ‘Circle’ to ‘Square’”. You don’t pass T yourself: Mojo works it out from the arguments. These square-bracket parameters are a big topic of their own, covered in Parameters and Generics.

A trait method can have a real body. That’s a default implementation: conforming structs get it for free, and can replace it with their own version. Defaults can call the required methods:

trait Shape:
def area(self) -> Float64:
...
def name(self) -> String:
return "shape"
def describe(self) -> String:
return self.name() + " with area " + String(self.area())
@fieldwise_init
struct Square(Shape):
var side: Float64
def area(self) -> Float64:
return self.side * self.side
def name(self) -> String:
return "square"
@fieldwise_init
struct Blob(Shape):
var size: Float64
def area(self) -> Float64:
return self.size
def main():
print(Square(3.0).describe())
print(Blob(7.5).describe())

Output:

square with area 9.0
shape with area 7.5

Square replaces name but keeps the default describe. Blob writes only the required area and keeps both defaults. This is how the standard library’s Equatable gives you != once you have ==.

A trait can refine another trait: it takes over all of its requirements and adds more. Write the parent trait in parentheses:

trait Named:
def name(self) -> String:
...
trait Greeter(Named):
def greet(self):
print("Hello, I'm", self.name())
@fieldwise_init
struct Robot(Greeter):
var id: Int
def name(self) -> String:
return "robot " + String(self.id)
def main():
var r = Robot(7)
r.greet()
print(r.name())

Output:

Hello, I'm robot 7
robot 7

Robot only lists Greeter, but it has to provide name too, because every Greeter is also Named. You’ve seen this in the standard library: Comparable refines Equatable, which is why a Comparable type also supports ==.

Join traits with & when a function needs more than one. The standard library traits work here just like your own:

def print_bigger[T: Comparable & Writable](a: T, b: T):
if a < b:
print(b)
else:
print(a)
@fieldwise_init
struct Score(Comparable, Writable):
var points: Int
def __lt__(self, other: Self) -> Bool:
return self.points < other.points
def main():
print_bigger(Score(3), Score(9))
print_bigger(12, 5)
print_bigger(String("apple"), String("banana"))

Output:

Score(points=9)
12
banana

One function works for your Score, for Int and for String, because all three are Comparable and Writable. If you use the same combination often, give it a name: comptime Printable = Comparable & Writable, then write [T: Printable].

Be aware of two limits that surprise people coming from Python or Java:

  • No list of mixed shapes. List[Shape] doesn’t compile (“‘List’ parameter ‘T’ has ‘AnyType’ type, but value has type ‘AnyTrait[Shape]’”). A trait isn’t a type you can store; a List holds one concrete type, like List[Square].
  • No adding traits to types you didn’t write. You can’t make Int or String conform to your Shape. Conformance is declared where the struct is defined.

The Mojo manual’s page on traits also covers trait members you won’t need yet, like associated types and required comptime values.

Write a trait Animal with a required method sound(self) -> String. Make Dog and Cat structs that conform, and a function speak(a: Some[Animal]) that prints It says woof or It says meow.

Hint: structs with no fields still need an initializer; @fieldwise_init works for them too.

Show solution
trait Animal:
def sound(self) -> String:
...
@fieldwise_init
struct Dog(Animal):
def sound(self) -> String:
return "woof"
@fieldwise_init
struct Cat(Animal):
def sound(self) -> String:
return "meow"
def speak(a: Some[Animal]):
print("It says", a.sound())
def main():
speak(Dog())
speak(Cat())

Output:

It says woof
It says meow

speak doesn’t know or care which animal it gets, only that it has sound.

Add a method intro(self) with a default body to Animal that prints I go <sound>!, using sound(). Then call Dog().intro(), without writing intro in Dog.

Hint: give the trait method a real body instead of ..., and call self.sound() inside it.

Show solution
trait Animal:
def sound(self) -> String:
...
def intro(self):
print("I go " + self.sound() + "!")
@fieldwise_init
struct Dog(Animal):
def sound(self) -> String:
return "woof"
def main():
Dog().intro()

Output:

I go woof!

Dog inherits intro from the trait. If it wrote its own intro, that one would be used instead.

  • A trait lists methods a type promises to have; ... marks a required method.
  • A struct conforms with struct Square(Shape): and the compiler checks every required method.
  • Some[Shape] accepts any conforming type; [T: Shape] names the type so you can use it twice.
  • Conformance must be declared; matching method names alone aren’t enough (no duck typing).
  • Traits can have default methods, can refine other traits, and can be combined with &.
  • You can’t make a List of a trait, and you can’t add traits to types you didn’t define.

Next up: common traits, a tour of the standard library traits like Copyable, Equatable and Hashable and what each one gives your types.

Quick check

1. What does ... mean as the body of a trait method?
2. A struct has an area method but does not list Shape. Can you pass it to def report(s: Some[Shape])?
3. Why write def f[T: Shape](a: T, b: T) instead of using Some[Shape] twice?
4. Which of these does NOT work in Mojo 1.2?