How can I use a fixed-size integer type to index a list?
I want to use a fixed-size integer value as index of a list. However, I get the "no matching method in call to 'getitem'" error.
How can I use a 32 bit unsigned integaer such as
ind
in the example above as index for a list (preferably without performance penalty and lengthy additional syntax)?5 Replies
IIRC list indexing takes an
Int
, so the only way is to wrap the index: l[int(ind)]
Thanks. I noticed I need to use the lower case
int
function. I have tested different versions and was not able to measure a significant performance penalty.Why would you expect a performance penalty? The
UInt32
version generates better assembly (despite having the int
to convince the type checker).I was not sure if the
int
is a function call (introducing some overhead, maybe copying of values). If it is really equivalent to a "reinterpret cast" in C++, then this is awesome. I do not yet have a feel for what is going on under the hood in mojo.My bad,
int
is correct. It actually is a function call: https://github.com/modularml/mojo/blob/8c35a418eadf31c7343887e1e2088a18d2d9f403/stdlib/src/builtin/int.mojo#L213
I'll trust sora that it actually generates better assembly 🙂GitHub
mojo/stdlib/src/builtin/int.mojo at 8c35a418eadf31c7343887e1e2088a1...
The Mojo Programming Language. Contribute to modularml/mojo development by creating an account on GitHub.