IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: 1.0
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

Sized

The Sized trait describes a type that has an integer length (such as a string or array).

Any type that conforms to Sized or SizedRaising works with the built-in len() function.

The Sized trait requires a type to implement the __len__() method. For example:

@fieldwise_init
struct Foo(Sized):
var length: Int

def __len__(self) -> Int:
return self.length

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

@fieldwise_init
struct Foo(Sized):
var length: Int

def __len__(self) -> Int:
return self.length

var foo = Foo(42)
print(len(foo) == 42)
True

Note: If the __len__() method can raise an error, use the SizedRaising trait instead.

Implemented traits

AnyType

Required methods

__len__

__len__(self: _Self) -> Int

Get the length of the type.

Returns:

Int: The length of the type.