typestar

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

  1. __init__ stores the width and height handed to it.
  2. area and perimeter read self.width and self.height without changing them.
  3. card.area() calls the method through the value, no free function needed.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 5 in A first struct, step 2 of 22 in Structs & traits.

← Previous Next →