Mojo Methods
A struct with only fields is a box of data. Methods are functions that live inside the struct and work with that data, so you can write rect.area() instead of area(rect). If you’ve written methods on a Python class, most of this will look familiar. The new part is that Mojo wants you to say whether a method only reads the struct or also changes it.
A method is a function inside a struct
Section titled “A method is a function inside a struct”You write a method with def, indented inside the struct, and its first argument is self:
@fieldwise_initstruct Rect: var width: Int var height: Int
def area(self) -> Int: return self.width * self.height
def perimeter(self) -> Int: return 2 * (self.width + self.height)
def main(): var r = Rect(4, 3) print(r.area()) print(r.perimeter())Output:
1214When you call r.area(), Mojo passes r as self for you. Inside the method, self.width and self.height are the fields of that particular rectangle. Unlike other arguments, self doesn’t need a type: Mojo already knows it’s a Rect.
Methods that take self are called instance methods, because you call them on an instance (a value) of the struct.
Methods can call other methods
Section titled “Methods can call other methods”Inside a method, you reach the other methods through self, the same way you reach the fields:
@fieldwise_initstruct Rect: var width: Int var height: Int
def area(self) -> Int: return self.width * self.height
def is_square(self) -> Bool: return self.width == self.height
def describe(self) -> String: var kind = "square" if self.is_square() else "rectangle" return kind + " with area " + String(self.area())
def main(): print(Rect(4, 3).describe()) print(Rect(5, 5).describe())Output:
rectangle with area 12square with area 25Writing just area() without self. wouldn’t work: Mojo would look for a normal function called area. Like in Python, self. is how you say “this struct’s”.
Changing fields needs mut self
Section titled “Changing fields needs mut self”Here’s a counter with a method that adds one. It looks right, but it doesn’t build:
@fieldwise_initstruct Counter: var count: Int
def increment(self): self.count += 1
def main(): var c = Counter(0) c.increment()hello.mojo:6:13: error: expression must be mutable for in-place operator destination self.count += 1 ~~~~^~~~~~mojo: error: failed to parse the provided Mojo source moduleBy default, self is read-only inside a method, just like normal function arguments. That’s a safety feature: when you call r.area(), you know it can’t change r. To let a method change the struct, write mut self:
@fieldwise_initstruct Counter: var count: Int
def increment(mut self): self.count += 1
def reset(mut self): self.count = 0
def main(): var c = Counter(0) c.increment() c.increment() c.increment() print(c.count) c.reset() print(c.count)Output:
30mut means the method gets the real c, not a copy, so its changes stay after it returns. The call looks the same either way: c.increment().
A mut method needs something it can change
Section titled “A mut method needs something it can change”A function argument is read-only too, unless you mark it. So you can’t call a mut method on it:
@fieldwise_initstruct Counter: var count: Int
def increment(mut self): self.count += 1
def add_two(c: Counter): c.increment() c.increment()
def main(): var c = Counter(0) add_two(c) print(c.count)hello.mojo:9:5: error: invalid call to 'increment': invalid use of mutating method on rvalue of type 'Counter' c.increment() ^~~~~~~~~~~hello.mojo:5:9: note: function declared here def increment(mut self): ^mojo: error: failed to parse the provided Mojo source moduleThe fix is the same keyword on the function argument: def add_two(mut c: Counter):. Then add_two(c) changes the caller’s counter and the program prints 2. The function arguments lesson showed mut on plain arguments; mut self is the same idea for the struct a method belongs to.
Methods that can fail
Section titled “Methods that can fail”A method can raise an error, just like a function. Add raises after the arguments:
@fieldwise_initstruct BankAccount: var owner: String var balance: Int
def deposit(mut self, amount: Int): self.balance += amount
def withdraw(mut self, amount: Int) raises: if amount > self.balance: raise Error("not enough money") self.balance -= amount
def main(): var acct = BankAccount("Ann", 100) acct.deposit(50) try: acct.withdraw(30) acct.withdraw(500) except e: print("error:", e) print(acct.owner, acct.balance)Output:
error: not enough moneyAnn 120The first withdraw works and the balance drops to 120. The second one raises before it touches balance, so the account stays at 120. Errors get their own lessons, starting with Mojo Errors.
Static methods
Section titled “Static methods”Sometimes a function belongs with a type but doesn’t need a particular value. A static method has no self, and you call it on the type itself. Mark it with @staticmethod:
@fieldwise_initstruct Temperature: var celsius: Float64
@staticmethod def from_fahrenheit(f: Float64) -> Self: return Self((f - 32.0) * 5.0 / 9.0)
@staticmethod def is_valid(celsius: Float64) -> Bool: return celsius >= -273.15
def fahrenheit(self) -> Float64: return self.celsius * 9.0 / 5.0 + 32.0
def main(): var boiling = Temperature.from_fahrenheit(212.0) print(boiling.celsius) print(boiling.fahrenheit()) print(Temperature.is_valid(-300.0))Output:
100.0212.0FalseTwo new things here:
Self(capital S) is a name for “the struct I’m inside”, hereTemperature.Self(...)builds a new one, and-> Selfsays the method returns one. If you rename the struct later,Selfkeeps working.Temperature.from_fahrenheit(212.0)is a common pattern: a static method that builds a value in a different way than__init__. People call these named constructors.
You can also call a static method on a value (boiling.is_valid(20.0)), but calling it on the type makes it clear that no value is involved. The @staticmethod reference has the details.
Constants that belong to a struct
Section titled “Constants that belong to a struct”A struct can hold compile-time constants with comptime. They aren’t fields: every value shares them, and they take no space inside the struct.
@fieldwise_initstruct Temperature: var celsius: Float64 comptime FREEZING = 0.0
def is_freezing(self) -> Bool: return self.celsius <= Self.FREEZING
def main(): print(Temperature(-5.0).is_freezing()) print(Temperature(12.5).is_freezing()) print(Temperature.FREEZING)Output:
TrueFalse0.0This is the closest thing Mojo has to a Python class attribute, but it can’t change at runtime. You met comptime in Mojo Constants.
Methods compared to Python
Section titled “Methods compared to Python”| Python | Mojo | |
|---|---|---|
| Instance method | def area(self): |
def area(self) -> Int: |
| Method that changes the object | Any method can | Needs def name(mut self): |
| Static method | @staticmethod |
@staticmethod (same) |
| Class method | @classmethod with cls |
Not available; use @staticmethod and Self |
| Class attribute | FREEZING = 0.0 in the class |
comptime FREEZING = 0.0 (constant only) |
The Mojo manual’s section on methods covers the same ground with more examples.
Practice
Section titled “Practice”1. A circle that can grow
Section titled “1. A circle that can grow”Make a Circle struct with a radius: Float64. Give it an area() method (use 3.14 * r * r) and a scale(factor) method that multiplies the radius. Print the area, scale by 2, and print it again.
Hint: scale changes a field, so it needs mut self.
Show solution
@fieldwise_initstruct Circle: var radius: Float64
def area(self) -> Float64: return 3.14 * self.radius * self.radius
def scale(mut self, factor: Float64): self.radius *= factor
def main(): var c = Circle(1.0) print(c.area()) c.scale(2.0) print(c.area())Output:
3.1412.56area only reads, so plain self is enough. scale uses mut self so the new radius sticks.
2. Fix the score keeper
Section titled “2. Fix the score keeper”This program should print 15, but it doesn’t build. Fix it.
@fieldwise_initstruct Score: var points: Int
def add(self, n: Int): self.points += n
def add_bonus(s: Score): s.add(5)
def main(): var s = Score(10) add_bonus(s) print(s.points)Hint: there are two places that need mut.
Show solution
@fieldwise_initstruct Score: var points: Int
def add(mut self, n: Int): self.points += n
def add_bonus(mut s: Score): s.add(5)
def main(): var s = Score(10) add_bonus(s) print(s.points)Output:
15add changes a field, so it needs mut self. add_bonus calls a mut method on its argument, so the argument needs mut too.
- A method is a
definside a struct; its first argument isself, the value you called it on. selfis read-only by default. Writemut selfto let a method change fields.- You can only call a
mutmethod on something mutable: avar, or an argument markedmut. - Methods can
raiseerrors, just like functions. @staticmethodmethods have noselfand are called on the type:Temperature.from_fahrenheit(212.0).Selfmeans “this struct’s type”.comptimemembers are constants shared by every value.
Next up: special methods, the double-underscore methods Mojo calls for you when you use ==, <, len() or [].
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo structs: methods: the manual’s section on instance methods,
mut selfand static methods. @staticmethod: the reference page for static methods.- Struct declarations reference: the rules for methods,
Selfandcomptimemembers. - Ownership and argument conventions: why
selfis read-only by default and whatmutreally means.