Skip to content

Mojo Printing Your Types

print(), String() and t-strings all work with numbers and strings out of the box. To make them work with your own structs, you add one trait: Writable. You can take the output Mojo writes for you, or decide exactly what it looks like. This is Mojo’s version of Python’s __str__ and __repr__, and it works a bit differently, so let’s go step by step.

Try to print a struct that doesn’t say it’s printable:

@fieldwise_init
struct Point:
var x: Int
var y: Int
def main():
var p = Point(3, 4)
print(p)
hello.mojo:8:11: error: invalid call to 'print': an element of 'values' with type 'Point' does not conform to trait 'Writable'; either prove the conformance with 'conforms_to', or add conformance
print(p)
~~~~~ ^
mojo: error: failed to parse the provided Mojo source module

print only accepts values whose type conforms to Writable. Python would print something like <__main__.Point object at 0x...>. Mojo refuses instead, because it has no general way to show a type you haven’t described.

The quickest fix is to add Writable in parentheses after the struct name. If all the fields are printable, Mojo writes the output for you:

@fieldwise_init
struct Point(Writable):
var x: Int
var y: Int
def main():
var p = Point(3, 4)
print(p)
print("Start:", p)
print(t"The point is {p}.")
var s = String(p)
print(s.upper())

Output:

Point(x=3, y=4)
Start: Point(x=3, y=4)
The point is Point(x=3, y=4).
POINT(X=3, Y=4)

One trait, and your struct works in every place that turns values into text: print, print with several values, t-strings and String(p). The default output shows the struct name and each field, which is often all you need while you’re writing and debugging code.

The automatic version prints each field, so each field’s type must be Writable too. Here Money isn’t:

@fieldwise_init
struct Money:
var cents: Int
@fieldwise_init
struct Item(Writable):
var name: String
var price: Money
def main():
var tea = Item("tea", Money(250))
print(tea)
hello.mojo:10:5: error: function instantiation failed
def main():
^
Mojo/stdlib/std/format/__init__.mojo:297:9: note: constraint failed: Could not derive Writable for Item - member field `price: Money` does not implement Writable
mojo: error: failed to run the pass manager

The real error has a long chain of notes; we kept the last one, which is the useful one: “Could not derive Writable for Item - member field price: Money does not implement Writable”. Add Writable to Money as well and it prints Item(name=tea, price=Money(cents=250)).

The default output is fine for debugging, but users of your program want (3, 4), not Point(x=3, y=4). To control the text, write a method called write_to:

@fieldwise_init
struct Point(Writable):
var x: Int
var y: Int
def write_to(self, mut writer: Some[Writer]):
writer.write("(", self.x, ", ", self.y, ")")
def main():
var p = Point(3, 4)
print(p)
print(t"Moved to {p}")
print(String(p).byte_length())

Output:

(3, 4)
Moved to (3, 4)
6

Here’s how to read that signature:

  • writer is wherever the text is going: the terminal for print, a new String for String(p), and so on. Your method doesn’t need to know which.
  • Some[Writer] means “any type that conforms to the Writer trait”. You’ll learn what Some[...] does in Mojo Traits; for now, copy the signature as it is.
  • mut writer, because writing into it changes it.
  • writer.write(...) takes any number of Writable values and writes them one after another, with no spaces in between. That’s why the example writes ", " itself.

Mojo writes your text straight into the destination, piece by piece. Python’s __str__ builds and returns a new string instead; Mojo’s way avoids making that extra string.

For anything longer, a t-string is easier to read than a list of pieces. A t-string has its own write_to, so you can hand it the writer:

@fieldwise_init
struct Temperature(Writable):
var city: String
var celsius: Float64
def write_to(self, mut writer: Some[Writer]):
t"{self.city}: {self.celsius} C".write_to(writer)
def main():
var t = Temperature("Oslo", -3.5)
print(t)
print("Today in", t)

Output:

Oslo: -3.5 C
Today in Oslo: -3.5 C

Remember that t-strings don’t support format specs like {x:.2f} (see String Formatting). If you need rounding, round the number before you write it.

The developer view: repr() and write_repr_to

Section titled “The developer view: repr() and write_repr_to”

Writable gives you two kinds of text, just like Python’s str and repr. print shows the friendly one. repr(x) shows a version for developers, with types and quotes so you can see exactly what’s inside:

@fieldwise_init
struct Pet(Writable):
var name: String
var age: Int
def main():
var p = Pet("Rex", 3)
print(p)
print(repr(p))

Output:

Pet(name=Rex, age=3)
Pet(name='Rex', age=Int(3))

In repr, the string has quotes and the number shows its type. To change the repr text, write write_repr_to, with the same signature as write_to:

@fieldwise_init
struct Point(Writable):
var x: Int
var y: Int
def write_to(self, mut writer: Some[Writer]):
writer.write("(", self.x, ", ", self.y, ")")
def write_repr_to(self, mut writer: Some[Writer]):
writer.write("Point(x=", self.x, ", y=", self.y, ")")
@fieldwise_init
struct Line(Writable):
var start: Point
var end: Point
def main():
var line = Line(Point(0, 0), Point(3, 4))
print(line)
print(repr(line))

Output:

Line(start=(0, 0), end=(3, 4))
Line(start=Point(x=0, y=0), end=Point(x=3, y=4))

Line uses the automatic output, and for its fields it calls Point’s own methods: write_to for print, write_repr_to for repr. So once a type knows how to print itself, every struct that contains it gets that for free.

print on a List works when the element type is printable, but there’s one more requirement: the elements must be Copyable. Without it you get a long error ending in “List iteration requires the element to be Copyable”. With both traits, a list prints using your write_to:

@fieldwise_init
struct Point(Writable, Copyable):
var x: Int
var y: Int
def write_to(self, mut writer: Some[Writer]):
writer.write("(", self.x, ", ", self.y, ")")
def main():
var path: List[Point] = [Point(0, 0), Point(1, 2), Point(3, 3)]
print(path)
print("Path has", len(path), "points, ends at", path[2])

Output:

[(0, 0), (1, 2), (3, 3)]
Path has 3 points, ends at (3, 3)

A String is a Writer too. So instead of String(p), which makes a new string, you can call write_to to add to a string you’re building:

@fieldwise_init
struct Point(Writable):
var x: Int
var y: Int
def write_to(self, mut writer: Some[Writer]):
writer.write("(", self.x, ", ", self.y, ")")
def main():
var report = String("Route: ")
Point(0, 0).write_to(report)
report += " -> "
Point(5, 2).write_to(report)
print(report)

Output:

Route: (0, 0) -> (5, 2)

You won’t need this often, but it’s how the Writable trait works underneath: everything that prints just calls write_to with a different writer.

Python Mojo
def __str__(self): return ... def write_to(self, mut writer: Some[Writer]):
def __repr__(self): return ... def write_repr_to(self, mut writer: Some[Writer]):
Every object prints something Only Writable types print; add the trait
str(p), f"{p}" String(p), t"{p}"
repr(p) repr(p) (same)

Mojo ignores methods named __str__ and __repr__, so don’t bring them over from Python code. The format package docs have more examples of Writable and Writer.

Make a Money struct holding cents: Int that prints like $22.54. Test it with Money(2254) and Money(705) (which should print $7.05).

Hint: self.cents // 100 gives the dollars and self.cents % 100 the cents. If the cents are below 10, write a "0" first.

Show solution
@fieldwise_init
struct Money(Writable):
var cents: Int
def write_to(self, mut writer: Some[Writer]):
var rest = self.cents % 100
writer.write("$", self.cents // 100, ".")
if rest < 10:
writer.write("0")
writer.write(rest)
def main():
print(Money(2254))
print(Money(705))

Output:

$22.54
$7.05

write_to is a normal method, so it can use if and call writer.write as many times as it likes.

Make a Date struct with year, month and day (all Int) that prints as 2026-11-26. Use a t-string inside write_to.

Hint: the month and day need a leading zero when they’re below 10. Build each part as a String first.

Show solution
def two_digits(n: Int) -> String:
if n < 10:
return "0" + String(n)
return String(n)
@fieldwise_init
struct Date(Writable):
var year: Int
var month: Int
var day: Int
def write_to(self, mut writer: Some[Writer]):
var m = two_digits(self.month)
var d = two_digits(self.day)
t"{self.year}-{m}-{d}".write_to(writer)
def main():
print(Date(2026, 11, 26))
print(Date(2027, 1, 5))

Output:

2026-11-26
2027-01-05

The helper function does the padding, and the t-string puts the pieces together. You can call ordinary functions from inside write_to.

  • print, String() and t-strings need a Writable type; plain structs fail to build.
  • Adding Writable gives you automatic output like Point(x=3, y=4), if every field is Writable.
  • Write write_to(self, mut writer: Some[Writer]) and call writer.write(...) to choose the text yourself.
  • repr(x) shows a developer view; customize it with write_repr_to.
  • Printing a List of your type also needs Copyable.
  • Mojo ignores __str__ and __repr__.

Next up: traits, the contracts behind Writable, Comparable and the rest, and how to write your own.

Quick check

1. What is the smallest change that makes print(p) work for a @fieldwise_init struct Point with two Int fields?
2. What does writer.write("(", self.x, ",", self.y, ")") print for x = 1 and y = 2?
3. Which method changes what repr(x) shows?
4. A struct is Writable, but printing a List of it fails with "List iteration requires the element to be Copyable". What do you add?