typestar

Two structs, one trait in Mojo

Unrelated types can satisfy the same trait, each in its own way.

trait Speaker:
    def speak(self) -> String:
        ...


@fieldwise_init
struct Dog(ImplicitlyCopyable, Movable, Speaker):
    var name: String

    def speak(self) -> String:
        return self.name + " says woof"


@fieldwise_init
struct Clock(ImplicitlyCopyable, Movable, Speaker):
    var hour: Int

    def speak(self) -> String:
        return "the time is " + String(self.hour)


def main():
    print(Dog("Rex").speak())
    print(Clock(9).speak())

How it works

  1. Speaker requires only that a type can produce a String.
  2. Dog builds its line from a name; Clock builds one from an hour.
  3. Neither struct knows about the other, yet both answer speak().

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
408
Tokens
103
Three-star pace
75 tpm

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

Type this snippet

Step 2 of 5 in Traits, step 17 of 22 in Structs & traits.

← Previous Next →