作为迭代器返回?,rust"/>

首页 > 解决方案 > 为什么 std::iter::Map 不能作为迭代器返回?

问题描述

我想将此行的映射部分变成一个函数:

let i: Vec<u32> = (0..=5).map(|x| x * 2).collect();

我编写了这段代码,我认为这将是我从原始代码中删除的内容的插入:

let j: Vec<u32> = process(0..=5).collect();
fn process<I>(src: I) -> I
where
    I: Iterator<Item = u32>,
{
    src.map(|x| x * 2)
}

我得到这个编译时错误:

error[E0308]: mismatched types
 --> src/lib.rs:5:5
  |
1 | fn process<I>(src: I) -> I
  |            -             - expected `I` because of return type
  |            |
  |            this type parameter
...
5 |     src.map(|x| x * 2)
  |     ^^^^^^^^^^^^^^^^^^ expected type parameter `I`, found struct `std::iter::Map`
  |
  = note: expected type parameter `I`
                     found struct `std::iter::Map<I, [closure@src/lib.rs:5:13: 5:22]>`

操场

既然std::iter::Map<u32, u32>实现了Iterator特征,它不应该能够返回Iterator<Item = u32>吗?

能够使它与以下内容一起工作:

fn process<I>(src: I) -> std::iter::Map<I, Box<dyn Fn(u32) -> u32>>
where
    I: Iterator<Item = u32>,
{
    src.map(Box::new(|x| x * 2))
}

这涉及将闭包包装在Box. 有没有更好或更简洁的方法来匹配内联函数?

标签: rust

解决方案


推荐阅读