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, Copyable, Movable):
    var s: String

    # Writer requirement to write a Span of Bytes
    fn write_bytes(mut self, bytes: Span[Byte, _]):
        self.s._iadd(bytes)

    # Writer requirement to take multiple args
    fn write[*Ts: Writable](mut self, *args: *Ts):
        @parameter
        for i in range(args.__len__()):
            args[i].write_to(self)

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


@fieldwise_init
struct Point(Writable, Copyable, Movable):
    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[W: Writer](self, mut writer: W):
        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, UnknownDestructibility

Methods

write_bytes

write_bytes(mut self: _Self, bytes: Span[SIMD[uint8, 1], origin])

Write a Span[Byte] to this Writer.

Args:

  • bytes (Span): The string slice to write to this Writer. Must NOT be null-terminated.

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?