I noticed an Iterable trait appeared in the nightly builds recently, and it looks like it’s getting quickly integrated into the stdlib.
I’d love to use it! … but how do you define a function with an argument whose type is bound by Iterable and also express type bounds on the iterated type?
The usual pattern of defining the type bound as Iterable[TheType] doesn’t seem to work here. Looks like Iterable is using an associated alias instead of a parameter? How do we express bounds on associated aliases in function arguments? I think the syntax in Rust for this is something like Iterable<IteratorType=TheType>. Does Mojo have something similar? Yet?
However, in the meantime your best bet is going to be using a rebind.
fn foo[I: Iterable](iter: I) -> List[Int]:
var result = List[Int]()
for element in iter:
result.append(rebind[Int](element))
return result^
The Iterator/Iterable API is still going to likely go through a handful of changes, but hopefully we will be able to make it easy to use w/out too much complexity of origins and the likes
Apologies I forgot to respond!
This is actually a known bug that has to do with list literals. (I’m pretty sure it’s getting fixed soon).
If you update the code to not use a literal it should work!
fn use_iterable[I: Iterable](iterable: I):
for _ in iterable:
pass
def main():
var values = List[Int](1, 2, 3)
use_iterable(values)
Looks like I’m getting the same crash even with a List instance, rather than a literal. My original encounter with this crash was a much more complicated case, and simplifying to literal usage didn’t change the result, so this seems consistent at least. This is on the newer 25.7.0.dev2025092205btw.
@cuchaz - Yes please! Thanks for finding this and it would be great to make a GitHub issue for this Internally we can figure out if this is already tracked or not and hopefully get a fix for it.