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.
Defining a trait
Section titled “Defining a trait”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.
Conforming to a trait
Section titled “Conforming to a trait”A struct conforms to a trait by listing it in parentheses and writing the required methods:
trait Shape: def area(self) -> Float64: ...
@fieldwise_initstruct Square(Shape): var side: Float64
def area(self) -> Float64: return self.side * self.side
@fieldwise_initstruct 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.03.14159So 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.
The compiler checks the contract
Section titled “The compiler checks the contract”If a struct claims a trait but forgets a method, it doesn’t build:
trait Shape: def area(self) -> Float64: ...
@fieldwise_initstruct 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 heretrait Shape: ^mojo: error: failed to parse the provided Mojo source moduleThe 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.
Functions that accept any shape
Section titled “Functions that accept any shape”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_initstruct Square(Shape): var side: Float64
def area(self) -> Float64: return self.side * self.side
@fieldwise_initstruct 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.0area: 12.56636Inside 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.
Conformance has to be declared
Section titled “Conformance has to be declared”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_initstruct 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 heredef report(s: Some[Shape]): ^mojo: error: failed to parse the provided Mojo source moduleThis 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.
Naming the type: [T: Shape]
Section titled “Naming the type: [T: Shape]”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_initstruct 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.0Read [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.
Default methods
Section titled “Default methods”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_initstruct Square(Shape): var side: Float64
def area(self) -> Float64: return self.side * self.side
def name(self) -> String: return "square"
@fieldwise_initstruct 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.0shape with area 7.5Square 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 ==.
Traits that build on other traits
Section titled “Traits that build on other traits”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_initstruct 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 7robot 7Robot 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 ==.
Asking for several traits at once
Section titled “Asking for several traits at once”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_initstruct 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)12bananaOne 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].
What traits can’t do (yet)
Section titled “What traits can’t do (yet)”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; aListholds one concrete type, likeList[Square]. - No adding traits to types you didn’t write. You can’t make
IntorStringconform to yourShape. 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.
Practice
Section titled “Practice”1. Animals that speak
Section titled “1. Animals that speak”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_initstruct Dog(Animal): def sound(self) -> String: return "woof"
@fieldwise_initstruct 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 woofIt says meowspeak doesn’t know or care which animal it gets, only that it has sound.
2. A default greeting
Section titled “2. A default greeting”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_initstruct 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
Listof 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo traits: the official manual page on defining, conforming to and combining traits.
- Trait declarations reference: the exact rules for required and provided methods, refinement and composition.
- Mojo traits cheat sheet: every standard library trait on one page.
- Parameterization: the square-bracket parameters behind
[T: Shape].