Methods on a struct in Mojo
Methods are functions that take self, so they can read the fields alongside them.
struct Rect(ImplicitlyCopyable, Movable):
var width: Float64
var height: Float64
def __init__(out self, width: Float64, height: Float64):
self.width = width
self.height = height
def area(self) -> Float64:
return self.width * self.height
def perimeter(self) -> Float64:
return 2.0 * (self.width + self.height)
def main():
var card = Rect(3.0, 4.0)
print(card.area(), card.perimeter())
How it works
__init__stores thewidthandheighthanded to it.areaandperimeterreadself.widthandself.heightwithout changing them.card.area()calls the method through the value, no free function needed.
Keywords and builtins used here
Float64Movableareadefmainperimeterprintreturnselfstructvar
The run, in numbers
- Lines
- 18
- Characters to type
- 388
- Tokens
- 99
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 70 seconds.
Step 2 of 5 in A first struct, step 2 of 22 in Structs & traits.