3 ms·
> can I have a function that takes a parameter of type Iter? fn example<I: Iterator>(iter: I) { ... } // or: fn example<I>(iter: I) where I: Iterator { .
by LegionMammal978 2y ago
> can I have a function that takes a parameter of type Iter?
fn example<I: Iterator>(iter: I) { ... }
// or:
fn example<I>(iter: I) where I: Iterator { ... }
// or:
fn example(iter: impl Iterator) { ... }
> Can it take any implementation of Iter than, regardless of what item type that returns?
Yes, in the above example. Then, the item type can be referred to as "<I as Iterator>::Item", or "I::Item" for short, unless you use the "impl Trait" syntax. You can also give the item type a name by giving it its own type parameter:
fn example<T, I: Iterator<Item = T>>(iter: I) { ... }
> How would I define a function that only accepts iterators that return, say, i32 items?
fn example<I: Iterator<Item = i32>>(iter: I) { ... }
// etc., just write Iterator<Item = i32> in place of Iterator