Skip to main content

Mojo trait

Writable

The Writable trait describes how a type is written into a Writer.

The Writable trait is designed for efficient output operations. It differs from Stringable in that Stringable merely converts a type to a String type, whereas Writable directly writes the type to an output stream, making it more efficient for output operations like print().

To make your type conform to Writable, you must implement write_to() which takes self and a type conforming to Writer:

struct Point(Writable):
    var x: Float64
    var y: Float64

    fn write_to(self, mut writer: Some[Writer]):
        var string = "Point"
        # Write a single `StringSlice`:
        writer.write_string(string)
        # Pass multiple args that implement `Writable`:
        writer.write("(", self.x, ", ", self.y, ")")

Implemented traits

AnyType, ImplicitlyDestructible

comptime members

__del__is_trivial

comptime __del__is_trivial

A flag (often compiler generated) to indicate whether the implementation of __del__ is trivial.

The implementation of __del__ is considered to be trivial if:

  • The struct has a compiler-generated trivial destructor and all its fields have a trivial __del__ method.

In practice, it means that the __del__ can be considered as no-op.

Required methods

write_to

write_to(self: _Self, mut writer: T)

Formats the string representation of this type to the provided Writer.

For example, when you pass your type to print(), it calls write_to() on your type and the writer is the FileDescriptor that print() is writing to.

Args:

  • writer (T): The type conforming to Writable.

Was this page helpful?