How to bound the type of Iterator::Item?

2019-02-16 13:10发布

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?

标签: rust
1条回答
甜甜的少女心
2楼-- · 2019-02-16 13:41

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);
}
查看更多
登录 后发表回答