Skip to main content
Log in

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:

@value
struct Foo(SizedRaising):
var length: Int

fn __len__(self) raises -> Int:
if self.length < 0:
raise Error("Length is negative")
return self.length
@value
struct Foo(SizedRaising):
var length: Int

fn __len__(self) raises -> Int:
if self.length < 0:
raise Error("Length is negative")
return self.length

You can pass an instance of Foo to the len() function to get its length:

fn main() raises:
var foo = Foo(42)
print(len(foo) == 42)
fn main() raises:
var foo = Foo(42)
print(len(foo) == 42)
True
True

Implemented traits

AnyType, UnknownDestructibility

Methods

__len__

__len__(self: _Self) -> Int

Get the length of the type.

Returns:

The length of the type.

Raises:

If the length cannot be computed.