Mojo trait
SizedRaising
The SizedRaising trait describes a type that has an integer length, which might raise an error if the length can't be determined.
Any type that conforms to Sized or
SizedRaising works with the built-in
len() function.
The SizedRaising trait requires a type to implement the __len__()
method, which can raise an error. For example:
struct Foo(SizedRaising):
var length: Int
fn __len__(self) raises -> Int:
if self.length < 0:
raise Error("Length is negative")
return self.lengthYou can pass an instance of Foo to the len() function to get its
length:
def main():
var foo = Foo(42)
print(len(foo) == 42)TrueImplemented traitsโ
Required methodsโ
__len__โ
__len__(self: _Self) -> Int
Get the length of the type.
Returns:
Int: The length of the type.
Raises:
If the length cannot be computed.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!