0Pricing
Mojo Academy · Lesson

Adding Methods to a Struct

Give your type behavior.

Data Plus Behavior

So far your struct only holds data. A method is a function that lives inside the struct and gives your type behavior. 🚀

Methods Live Inside

You write a method by defining a function indented inside the struct, right alongside its fields and __init__.

struct Point:
    var x: Int
    var y: Int
    fn show(self):
        print(self.x, self.y)

All lessons in this course

  1. Defining a struct
  2. Fields and the __init__ Method
  3. Adding Methods to a Struct
  4. Structs vs Python Classes
← Back to Mojo Academy