Skip to content

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.

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 4
10 4

Let’s go through it line by line:

  • struct Point: starts the struct. Type names use PascalCase.
  • var x: Int declares a field, a piece of data every Point carries. Fields always need var and a type.
  • def __init__(out self, x: Int, y: Int): is the initializer. Mojo runs it when you write Point(3, 4). Its job is to give every field a value.
  • self is the point being built. You never pass it yourself: Point(3, 4) passes only x and y.
  • out self means “self starts empty and this function fills it in”. You’ll see out on every __init__. The argument conventions lesson explains it fully.
  • p.x reads a field and p.x = 10 changes it, with a dot, like in Python.

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 manager

In Python, a forgotten attribute only fails later, when some code tries to read it. In Mojo, a half-built value can’t exist.

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_init
struct 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 30
Bo 25

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

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 here
def __init__(out self, *, deinit move: Self) # note - generated function
^
mojo: error: failed to parse the provided Mojo source module

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

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():
pass
hello.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 module

Fields 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 2
7 1
3 3

Rect(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.

A Python object lets you attach new attributes whenever you like. A Mojo struct has exactly the fields you declared, and nothing else:

@fieldwise_init
struct Point:
var x: Int
var y: Int
def main():
var p = Point(1, 2)
p.z = 5
hello.mojo:8:6: error: 'Point' value has no attribute 'z'
p.z = 5
~^
mojo: error: failed to parse the provided Mojo source module

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

A field can be any type, including another struct. Here’s a line made of two points:

@fieldwise_init
struct Point:
var x: Int
var y: Int
@fieldwise_init
struct 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 4
0 2

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

Two things you’ll try right away don’t work on a plain struct: print(p) and var q = p.

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

Mojo 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_init
struct 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.

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.

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

b.author + "," glues the comma onto the name, so print doesn’t put a space before it.

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 True

The fields are only declared at the top. __init__ gives them their starting values, and Thermostat() calls it with no arguments.

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_init
struct Position:
var row: Int
var col: Int
@fieldwise_init
struct 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 3

Player 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_init writes 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 Writable and ImplicitlyCopyable.

Next up: methods, giving your structs functions of their own.

Quick check

1. What does @fieldwise_init do?
2. Which field declaration is valid in a Mojo struct?
3. You get "missing required argument: 'move'" when you call Point(1, 2). What is the most likely cause?
4. How do you reuse the fields of an Animal struct in a Dog struct?

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