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
write_to(self, mut writer: Some[Writer])is the one methodWritableasks for.writer.write(...)takes several pieces at once and streams them out.print(today)uses it directly, andString(today)captures the same text.
Keywords and builtins used here
Float64MovableStringdefmainprintselfstructvarwrite_to
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.
Step 5 of 5 in Operators, step 15 of 22 in Structs & traits.