Mojo Structs
So far you’ve used types that come with Mojo: Int, String, List and friends. A struct lets you make your own type, with named pieces of data that belong together. A point has an x and a y, a user has a name and an age, and a struct lets you keep them in one value. If you know Python, a struct plays the role of a class, but it’s stricter: everything about it is fixed when the program compiles.
Your first struct
Section titled “Your first struct”Here’s a struct for a point on a grid:
struct Point: var x: Int var y: Int
def __init__(out self, x: Int, y: Int): self.x = x self.y = y
def main(): var p = Point(3, 4) print(p.x, p.y) p.x = 10 print(p.x, p.y)Output:
3 410 4Let’s go through it line by line:
struct Point:starts the struct. Type names usePascalCase.var x: Intdeclares a field, a piece of data everyPointcarries. Fields always needvarand a type.def __init__(out self, x: Int, y: Int):is the initializer. Mojo runs it when you writePoint(3, 4). Its job is to give every field a value.selfis the point being built. You never pass it yourself:Point(3, 4)passes onlyxandy.out selfmeans “selfstarts empty and this function fills it in”. You’ll seeouton every__init__. The argument conventions lesson explains it fully.p.xreads a field andp.x = 10changes it, with a dot, like in Python.
Every field needs a value
Section titled “Every field needs a value”The initializer must set every field. If you forget one, Mojo won’t build the program:
struct Point: var x: Int var y: Int
def __init__(out self, x: Int): self.x = x
def main(): var p = Point(1) print(p.x)hello.mojo:5:9: error: 'self.y' is uninitialized at the implicit return from this function def __init__(out self, x: Int): ^hello.mojo:5:22: note: 'self' declared here def __init__(out self, x: Int): ^mojo: error: failed to run the pass managerIn Python, a forgotten attribute only fails later, when some code tries to read it. In Mojo, a half-built value can’t exist.
Skip the boilerplate with @fieldwise_init
Section titled “Skip the boilerplate with @fieldwise_init”Most initializers just copy each argument into the field with the same name. That’s so common that Mojo can write it for you. Put @fieldwise_init above the struct:
@fieldwise_initstruct User: var name: String var age: Int
def main(): var a = User("Ann", 30) var b = User(name="Bo", age=25) print(a.name, a.age) print(b.name, b.age)Output:
Ann 30Bo 25The decorator creates an __init__ that takes one argument per field, in the order you declared them. Because the arguments have the field names, you can pass them by keyword too, as in User(name="Bo", age=25). The @fieldwise_init reference shows exactly what it generates.
No initializer, no values
Section titled “No initializer, no values”If a struct has neither @fieldwise_init nor an __init__, you can’t create one at all. The error message is a bit confusing:
struct Point: var x: Int var y: Int
def main(): var p = Point(1, 2) print(p.x)hello.mojo:6:18: error: invalid initialization: missing required argument: 'move' var p = Point(1, 2) ~~~~~^~~~~~hello.mojo:1:1: note: function declared heredef __init__(out self, *, deinit move: Self) # note - generated function^mojo: error: failed to parse the provided Mojo source moduleThe only initializer Mojo found is one it made by itself, for moving an existing Point. It doesn’t take 1, 2, so the call fails. When you see “missing required argument: ‘move’”, you’ve most likely forgotten @fieldwise_init or your __init__.
Fields can’t have default values
Section titled “Fields can’t have default values”In Python you might write x: int = 0 in a dataclass. In a Mojo struct, that’s an error:
struct Settings: var volume: Int = 5
def main(): passhello.mojo:2:21: error: unknown tokens at the end of a declaration var volume: Int = 5 ^mojo: error: failed to parse the provided Mojo source moduleFields get their values in __init__, and only there. To have a default, give the initializer argument a default value instead. You can also write more than one __init__, as long as their arguments differ:
struct Rect: var width: Int var height: Int
def __init__(out self, width: Int, height: Int = 1): self.width = width self.height = height
def __init__(out self, *, side: Int): self.width = side self.height = side
def main(): var a = Rect(4, 2) var b = Rect(7) var c = Rect(side=3) print(a.width, a.height) print(b.width, b.height) print(c.width, c.height)Output:
4 27 13 3Rect(7) uses the default height = 1. The second __init__ has a * before side, which makes side keyword-only, so Rect(side=3) clearly means “a square”. This is the same overloading you’ve seen for functions.
You can’t add fields later
Section titled “You can’t add fields later”A Python object lets you attach new attributes whenever you like. A Mojo struct has exactly the fields you declared, and nothing else:
@fieldwise_initstruct Point: var x: Int var y: Int
def main(): var p = Point(1, 2) p.z = 5hello.mojo:8:6: error: 'Point' value has no attribute 'z' p.z = 5 ~^mojo: error: failed to parse the provided Mojo source moduleThis is part of why structs are fast: the compiler knows the exact layout of every Point before the program runs, so reading p.x is a direct memory access, with no lookup by name.
Structs inside structs
Section titled “Structs inside structs”A field can be any type, including another struct. Here’s a line made of two points:
@fieldwise_initstruct Point: var x: Int var y: Int
@fieldwise_initstruct Line: var start: Point var end: Point
def main(): var line = Line(Point(0, 0), Point(3, 4)) print(line.end.x, line.end.y) line.start.y = 2 print(line.start.x, line.start.y)Output:
3 40 2You reach the inner fields with more dots: line.end.x. This is also how you reuse code in Mojo. There’s no inheritance: a struct can’t extend another struct. Instead of “a Dog is an Animal”, you write “a Dog has an Animal field”, or you share behavior with traits.
Printing and copying a whole struct
Section titled “Printing and copying a whole struct”Two things you’ll try right away don’t work on a plain struct: print(p) and var q = p.
@fieldwise_initstruct Point: var x: Int var y: Int
def main(): var p = Point(1, 2) var q = p print(q.x)hello.mojo:8:13: error: value of type 'Point' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable' var q = p ^mojo: error: failed to parse the provided Mojo source moduleMojo doesn’t assume your type can be printed or copied. You opt in by listing traits in parentheses after the name. For now, here’s the short version:
@fieldwise_initstruct Point(ImplicitlyCopyable, Writable): var x: Int var y: Int
def main(): var p = Point(1, 2) var q = p q.x = 99 print(p) print(q)Output:
Point(x=1, y=2)Point(x=99, y=2)Writable makes print(p) work, and ImplicitlyCopyable lets var q = p make a copy. Changing q doesn’t touch p: each variable owns its own Point. That’s different from Python, where q = p makes both names point at the same object. You’ll learn the details in Printing Your Types, Common Traits and Value Semantics.
Structs compared to Python classes
Section titled “Structs compared to Python classes”| Python class | Mojo struct | |
|---|---|---|
| Declare fields | Optional, can appear anywhere | Required: var name: Type in the struct body |
| Default field values | x: int = 0 |
Not allowed; use default arguments in __init__ |
| Add attributes at runtime | Yes | No, the layout is fixed |
| Inheritance | Yes | No; use fields (composition) and traits |
q = p |
Both names share one object | Makes a copy (if the type allows it) |
The official Mojo manual’s page on structs says Mojo plans to add Python-style classes one day. For now, structs are the way to make your own types, and the standard library’s Int, String and List are structs too.
Practice
Section titled “Practice”1. A book
Section titled “1. A book”Make a struct Book with a title (String), an author (String) and pages (Int). Create one and print Dune by Frank Herbert, 412 pages.
Hint: @fieldwise_init saves you from writing __init__. Print the fields with print(b.title, "by", ...).
Show solution
@fieldwise_initstruct Book: var title: String var author: String var pages: Int
def main(): var b = Book("Dune", "Frank Herbert", 412) print(b.title, "by", b.author + ",", b.pages, "pages")Output:
Dune by Frank Herbert, 412 pagesb.author + "," glues the comma onto the name, so print doesn’t put a space before it.
2. Fix the struct
Section titled “2. Fix the struct”This code is written like a Python dataclass. Make it work in Mojo so it prints 21 True.
struct Thermostat: target: Int = 21 is_on: Bool = True
def main(): var t = Thermostat() print(t.target, t.is_on)Hint: fields need var and no = value. Put the defaults in an __init__ that takes no arguments.
Show solution
struct Thermostat: var target: Int var is_on: Bool
def __init__(out self): self.target = 21 self.is_on = True
def main(): var t = Thermostat() print(t.target, t.is_on)Output:
21 TrueThe fields are only declared at the top. __init__ gives them their starting values, and Thermostat() calls it with no arguments.
3. A player with a position
Section titled “3. A player with a position”Make a Position struct (row, col) and a Player struct with a name and a pos: Position. Create a player at row 0, column 0, move them to column 3, and print Kim 0 3.
Hint: change the inner field with player.pos.col = 3.
Show solution
@fieldwise_initstruct Position: var row: Int var col: Int
@fieldwise_initstruct Player: var name: String var pos: Position
def main(): var player = Player("Kim", Position(0, 0)) player.pos.col = 3 print(player.name, player.pos.row, player.pos.col)Output:
Kim 0 3Player holds a whole Position inside it. Dots go as deep as the nesting does.
- A struct is your own type: a group of named fields, each declared with
var name: Type. __init__(out self, ...)builds a value and must set every field.@fieldwise_initwrites the usual “one argument per field” initializer for you.- Fields can’t have default values and you can’t add fields at runtime; use default arguments in
__init__. - There’s no inheritance: put structs inside structs, and share behavior with traits.
- Printing and copying are opt-in through traits like
WritableandImplicitlyCopyable.
Next up: methods, giving your structs functions of their own.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo structs: the official manual page on fields, initializers, methods and how structs compare to classes.
- Struct declarations reference: the exact rules for fields, initializers and trait conformance.
@fieldwise_init: what the decorator generates, including its implicit conversion option.- Creating values: how initializers work in detail, including the copy and move initializers.