Reputation: 2642
I'm not sure how to specify bounds on the type of the output of the iterator for generic iterators. Before Rust 1.0, I used to be able to do this:
fn somefunc<A: Int, I: Iterator<A>>(xs: I) {
xs.next().unwrap().pow(2);
}
But now, I'm not sure how to put bounds on the iterator's Item
type.
fn somefunc<I: Iterator>(xs: I) {
xs.next().unwrap().pow(2);
}
error: no method named `pow` found for type `<I as std::iter::Iterator>::Item` in the current scope
--> src/main.rs:2:28
|
2 | xs.next().unwrap().pow(2);
| ^^^
How can I get this to work?
Upvotes: 12
Views: 3347
Reputation: 127831
You can introduce a second generic type parameter and place the bound on that:
fn somefunc<A: Int, I: Iterator<Item = A>>(mut xs: I) {
xs.next().unwrap().pow(2);
}
You can also place trait bounds on the associated type itself
fn somefunc<I: Iterator>(mut xs: I)
where
I::Item: Int,
{
xs.next().unwrap().pow(2);
}
Upvotes: 21