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
trait Greeter:listsgreetingwith...standing in for the body.Robotclaims the trait in its header and then has to implement it.- The compiler checks conformance up front, so the call cannot miss.
Keywords and builtins used here
MovableStringdefgreetingmainprintreturnselfstructtraitvar
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.
Step 1 of 5 in Traits, step 16 of 22 in Structs & traits.