为什么 std::iter::Map<I, F> 不能作为 Iterator<Item = I> 返回?

Jor*_*dan 5 rust

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

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

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

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

我得到这个编译时错误:

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]>`
Run Code Online (Sandbox Code Playgroud)

操场

既然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))
}
Run Code Online (Sandbox Code Playgroud)

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