Skip to main content
Log in

Mojo trait

IntableRaising

The IntableRaising trait describes a type can be converted to an Int, but the conversion might raise an error.

Any type that conforms to Intable or IntableRaising works with the built-in int() function.

This trait requires the type to implement the __int__() method, which can raise an error. For example:

@value
struct Foo(IntableRaising):
var i: Int

fn __int__(self) raises -> Int:
return self.i
@value
struct Foo(IntableRaising):
var i: Int

fn __int__(self) raises -> Int:
return self.i

Now you can use the int() function to convert a Foo to an Int:

fn main() raises:
var x = Foo(42)
print(int(x) == 42)
fn main() raises:
var x = Foo(42)
print(int(x) == 42)
True
True

Implemented traits

AnyType

Methods

__int__

__int__(self: T) -> Int

Get the integral representation of the value.

Returns:

The integral representation of the type.

Raises:

If the type does not have an integral representation.

Was this page helpful?