Mojo trait
Stringable
The Stringable trait describes a type that can be converted to a String.
Any type that conforms to Stringable or
StringableRaising works
with the built-in print() and
String() functions.
The Stringable trait requires the type to define the __str__() method.
For example:
struct Foo(Stringable):
    var s: String
    fn __str__(self) -> String:
        return self.sNow you can pass an instance of Foo to the String() function to get back a
String:
var foo = Foo("test")
print(String(foo) == "test")TrueNote: If the __str__() method might raise an error, use the
StringableRaising
trait, instead.
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.
This method 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,
UnknownDestructibility
Aliases
__del__is_trivial
alias __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
__str__
__str__(self: _Self) -> String
Get the string representation of the type.
Returns:
String: The string representation of the type.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!
