Skip to main content

Mojo trait

Stringable

The Stringable trait describes a type that can be converted to a String.

Any type that conforms to Stringable works with the built-in print() function and implicitly converts to a String.

The Stringable trait requires the type to define the __str__() method. For example:

@fieldwise_init
struct Foo(Stringable):
    var s: String

    fn __str__(self) -> String:
        return self.s

Now you can pass an instance of Foo to the String() function to get back a String:

var foo = Foo("test")
print(String(foo) == "test")
True

About the difference between __repr__() and __str__(): The method __repr__ computes the "official" string representation of an object while __str__() computes the "informal" or nicely printable string representation of an object.

__str__() differs from __repr__() in that there is no expectation that __str__() return a valid Mojo expression: a more convenient or concise representation can be used.

Implemented traitsโ€‹

AnyType

Required methodsโ€‹

__str__โ€‹

__str__(self: _Self) -> String

Get the string representation of the type.

Returns:

String: The string representation of the type.

Was this page helpful?