M
Modular•4mo ago
samufi

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.
var l: List[Int] = List[Int]()
l.append(1)
var ind: UInt32 = 0
print(l[ind])
var l: List[Int] = List[Int]()
l.append(1)
var ind: UInt32 = 0
print(l[ind])
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
Jake Brooks
Jake Brooks•4mo ago
IIRC list indexing takes an Int, so the only way is to wrap the index: l[int(ind)]
samufi
samufiOP•4mo ago
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.
sora
sora•4mo ago
Why would you expect a performance penalty? The UInt32 version generates better assembly (despite having the int to convince the type checker).
samufi
samufiOP•3mo ago
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.
Jake Brooks
Jake Brooks•3mo ago
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.
Want results from more Discord servers?
Add your server