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.
Printing a plain struct fails
Section titled “Printing a plain struct fails”Try to print a struct that doesn’t say it’s printable:
@fieldwise_initstruct 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 moduleprint 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.
Add Writable and you’re done
Section titled “Add Writable and you’re done”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_initstruct 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.
Every field has to be printable
Section titled “Every field has to be printable”The automatic version prints each field, so each field’s type must be Writable too. Here Money isn’t:
@fieldwise_initstruct Money: var cents: Int
@fieldwise_initstruct 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 faileddef 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 Writablemojo: error: failed to run the pass managerThe 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)).
Choose your own format: write_to
Section titled “Choose your own format: write_to”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_initstruct 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)6Here’s how to read that signature:
writeris wherever the text is going: the terminal forprint, a newStringforString(p), and so on. Your method doesn’t need to know which.Some[Writer]means “any type that conforms to theWritertrait”. You’ll learn whatSome[...]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 ofWritablevalues 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.
Using a t-string in write_to
Section titled “Using a t-string in write_to”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_initstruct 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 CToday in Oslo: -3.5 CRemember 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_initstruct 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_initstruct 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_initstruct 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.
Lists of your type
Section titled “Lists of your type”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_initstruct 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)Writing into a String you already have
Section titled “Writing into a String you already have”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_initstruct 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.
Coming from Python
Section titled “Coming from Python”| 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.
Practice
Section titled “Practice”1. Show money properly
Section titled “1. Show money properly”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_initstruct 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.05write_to is a normal method, so it can use if and call writer.write as many times as it likes.
2. A date with a t-string
Section titled “2. A date with a t-string”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_initstruct 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-262027-01-05The 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 aWritabletype; plain structs fail to build.- Adding
Writablegives you automatic output likePoint(x=3, y=4), if every field isWritable. - Write
write_to(self, mut writer: Some[Writer])and callwriter.write(...)to choose the text yourself. repr(x)shows a developer view; customize it withwrite_repr_to.- Printing a
Listof your type also needsCopyable. - Mojo ignores
__str__and__repr__.
Next up: traits, the contracts behind Writable, Comparable and the rest, and how to write your own.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”Writabletrait: the trait’s methods and the default output it provides.Writertrait: what a writer is, and how to write your own.- The
formatpackage: short examples of default, custom andreproutput. TString: how t-strings work, includingwrite_to.