Mojo trait
Intable
The Intable
trait describes a type that can be converted to an Int.
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. For
example:
@value
struct Foo(Intable):
var i: Int
fn __int__(self) -> Int:
return self.i
@value
struct Foo(Intable):
var i: Int
fn __int__(self) -> Int:
return self.i
Now you can use the int()
function to convert a Foo
to an
Int
:
foo = Foo(42)
assert_equal(int(foo), 42)
foo = Foo(42)
assert_equal(int(foo), 42)
Note: If the __int__()
method can raise an error, use the
IntableRaising
trait
instead.
Implemented traits
AnyType
,
CollectionElement
,
Copyable
,
Movable
Methods
__copyinit__
__copyinit__(out self: T, existing: T, /)
Create a new instance of the value by copying an existing one.
Args:
- existing (
T
): The value to copy.
__moveinit__
__moveinit__(out self: T, owned existing: T, /)
Create a new instance of the value by moving the value of another.
Args:
- existing (
T
): The value to move.
__int__
__int__(self: T) -> Int
Get the integral representation of the value.
Returns:
The integral representation of the value.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!