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
Speakerrequires only that a type can produce aString.Dogbuilds its line from a name;Clockbuilds one from an hour.- Neither struct knows about the other, yet both answer
speak().
Keywords and builtins used here
IntMovableStringdefmainprintreturnselfspeakstructtraitvar
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.
Step 2 of 5 in Traits, step 17 of 22 in Structs & traits.