Re:Fear Not the Association of Types
by AlotOfReading on Sunday August 18, 2024 @04:28PM
(#41285223)
You'd write it as a type parameter with a type bound. There's a couple of different ways to write it, but one example:
fn foo<I>(it: I) where I : Iterator<Item = i32> {}
Re:Fear Not the Association of Types
by LegionMammal978 on Sunday August 18, 2024 @04:31PM
(#41285250)
> 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
I'm not sure how or if Rust traits can be used as function parameters - can I have a function that takes a parameter of type Iter? Can it take any implementation of Iter than, regardless of what item type that returns? How would I define a function that only accepts iterators that return, say, i32 items?