如何绑定 Iterator::Item 的类型? [英] How to bound the type of Iterator::Item?

查看:54
本文介绍了如何绑定 Iterator::Item 的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何为泛型迭代器指定迭代器输出类型的界限.在 Rust 1.0 之前,我曾经可以这样做:

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);
}

但是现在,我不确定如何在迭代器的 Item 类型上设置边界.

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?

推荐答案

您可以引入第二个泛型类型参数并对其进行绑定:

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);
}

这篇关于如何绑定 Iterator::Item 的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆