Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bound the type of Iterator::Item?

Tags:

rust

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?

like image 830
awelkie Avatar asked Jan 06 '15 15:01

awelkie


1 Answers

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);
}
like image 77
Vladimir Matveev Avatar answered Oct 23 '22 17:10

Vladimir Matveev