Skip to content

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.

You write a method with def, indented inside the struct, and its first argument is self:

@fieldwise_init
struct 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:

12
14

When 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.

Inside a method, you reach the other methods through self, the same way you reach the fields:

@fieldwise_init
struct 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 12
square with area 25

Writing 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”.

Here’s a counter with a method that adds one. It looks right, but it doesn’t build:

@fieldwise_init
struct 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 module

By 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_init
struct 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:

3
0

mut 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_init
struct 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 module

The 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.

A method can raise an error, just like a function. Add raises after the arguments:

@fieldwise_init
struct 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 money
Ann 120

The 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.

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_init
struct 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.0
212.0
False

Two new things here:

  • Self (capital S) is a name for “the struct I’m inside”, here Temperature. Self(...) builds a new one, and -> Self says the method returns one. If you rename the struct later, Self keeps 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.

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_init
struct 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:

True
False
0.0

This is the closest thing Mojo has to a Python class attribute, but it can’t change at runtime. You met comptime in Mojo Constants.

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.

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_init
struct 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.14
12.56

area only reads, so plain self is enough. scale uses mut self so the new radius sticks.

This program should print 15, but it doesn’t build. Fix it.

@fieldwise_init
struct 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_init
struct 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:

15

add 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 def inside a struct; its first argument is self, the value you called it on.
  • self is read-only by default. Write mut self to let a method change fields.
  • You can only call a mut method on something mutable: a var, or an argument marked mut.
  • Methods can raise errors, just like functions.
  • @staticmethod methods have no self and are called on the type: Temperature.from_fahrenheit(212.0).
  • Self means “this struct’s type”. comptime members 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

1. Why does def increment(self): self.count += 1 fail to build?
2. How do you call a static method from_fahrenheit on the Temperature struct?
3. What does Self mean inside a struct?
4. A function def bump(c: Counter) calls c.increment(), which is a mut method. What do you change?