Skip to main content

Mojo trait

Writer

Describes a type that can be written to by any type that implements the write_to function.

This enables you to write one implementation that can be written to a variety of types such as file descriptors, strings, network locations etc. The types are written as a Span[Byte], so the Writer can avoid allocations depending on the requirements. There is also a general write that takes multiple args that implement write_to.

Example:

from memory import Span

@fieldwise_init
struct NewString(Writer, Writable, ImplicitlyCopyable):
    var s: String

    # Writer requirement to write a String
    fn write_string(mut self, string: StringSlice):
        self.s += string

    # Also make it Writable to allow `print` to write the inner String
    fn write_to(self, mut writer: Some[Writer]):
        writer.write(self.s)


@fieldwise_init
struct Point(Writable, ImplicitlyCopyable):
    var x: Int
    var y: Int

    # Pass multiple args to the Writer. The Int and StaticString types
    # call `writer.write_bytes` in their own `write_to` implementations.
    fn write_to(self, mut writer: Some[Writer]):
        writer.write("Point(", self.x, ", ", self.y, ")")

    # Enable conversion to a String using `String(point)`
    fn __str__(self) -> String:
        return String.write(self)


fn main():
    var point = Point(1, 2)
    var new_string = NewString(String(point))
    new_string.write("\n", Point(3, 4))
    print(new_string)

Output:

Point(1, 2)
Point(3, 4)

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_string

write_string(mut self: _Self, string: StringSlice[origin])

Write a StringSlice to this Writer.

Args:

  • string (StringSlice): The string slice to write to this Writer.

Provided methods

write

write[*Ts: Writable](mut self: _Self, *args: *Ts)

Write a sequence of Writable arguments to the provided Writer.

Parameters:

  • *Ts (Writable): Types of the provided argument sequence.

Args:

  • *args (*Ts): Sequence of arguments to write to this Writer.

Was this page helpful?