#How can I use a fixed-size integer type to index a list?

7 messages · Page 1 of 1 (latest)

shell halo
#

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])

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)?

#

How can I use a fixed-size integer type to index a list?

open valley
#

IIRC list indexing takes an Int, so the only way is to wrap the index: l[int(ind)]

shell halo
#

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.

vagrant pier
#

Why would you expect a performance penalty? The UInt32 version generates better assembly (despite having the int to convince the type checker).

shell halo
#

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.

candid bisonBOT