typestar

Declaring a trait in Mojo

A trait names the methods a type must supply, without saying how.

trait Greeter:
    def greeting(self) -> String:
        ...


@fieldwise_init
struct Robot(ImplicitlyCopyable, Movable, Greeter):
    var model: String

    def greeting(self) -> String:
        return "unit " + self.model + " online"


def main():
    var arm = Robot("K9")
    print(arm.greeting())

How it works

  1. trait Greeter: lists greeting with ... standing in for the body.
  2. Robot claims the trait in its header and then has to implement it.
  3. The compiler checks conformance up front, so the call cannot miss.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
265
Tokens
68
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 51 seconds.

Type this snippet

Step 1 of 5 in Traits, step 16 of 22 in Structs & traits.

← Previous Next →