【问题标题】:How to bound the type of Iterator::Item?如何绑定 Iterator::Item 的类型?
【发布时间】:2015-01-06 15:28:21
【问题描述】:

我不确定如何为泛型迭代器指定迭代器输出类型的界限。在 Rust 1.0 之前,我曾经能够做到这一点:

fn somefunc<A: Int, I: Iterator<A>>(xs: I) {
    xs.next().unwrap().pow(2);
}

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

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

我怎样才能让它工作?

【问题讨论】:

    标签: rust


    【解决方案1】:

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

    fn somefunc<A: Int, I: Iterator<Item = A>>(mut xs: I) {
        xs.next().unwrap().pow(2);
    }
    

    您还可以在关联类型本身上放置 trait bound

    fn somefunc<I: Iterator>(mut xs: I)
    where
        I::Item: Int,
    {
        xs.next().unwrap().pow(2);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 2021-05-14
      • 2015-11-20
      • 1970-01-01
      • 2011-06-30
      相关资源
      最近更新 更多