typestar

Printable structs in Mojo

Conform to Writable and your struct prints itself, no formatting helper required.

@fieldwise_init
struct Reading(ImplicitlyCopyable, Movable, Writable):
    var city: String
    var degrees: Float64

    def write_to(self, mut writer: Some[Writer]):
        writer.write(self.city, " at ", self.degrees, " degrees")


def main():
    var today = Reading("Austin", 98.6)
    print(today)
    print(String(today).upper())

How it works

  1. write_to(self, mut writer: Some[Writer]) is the one method Writable asks for.
  2. writer.write(...) takes several pieces at once and streams them out.
  3. print(today) uses it directly, and String(today) captures the same text.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
305
Tokens
77
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 62 seconds.

Type this snippet

Step 5 of 5 in Operators, step 15 of 22 in Structs & traits.

← Previous Next →