std::iter::FlatMap.clone() 可能吗?

Is std::iter::FlatMap.clone() possible?

我正在尝试在 FlatMap:

中创建所有可能的项目对
possible_children.clone().flat_map(|a| possible_children.clone().map(|b| (a,b)))

为了做到这一点,我试图克隆一个 FlatMap 并且我在文档中看到 FlatMap 结构实现了一个 clone 方法。但是似乎不可能创建满足特征界限的FlatMap

这是我收到的错误:

error: no method named `clone` found for type `std::iter::FlatMap<std::ops::Range<u16>, _, [closure@src/main.rs:30:47: 33:27]>` in the current scope
  --> src/main.rs:37:66
   |
37 |         possible_children.clone().flat_map(|a| possible_children.clone().map(|b| (a,b)))
   |                                                                  ^^^^^
   |
   = note: the method `clone` exists but the following trait bounds were not satisfied: `[closure@src/main.rs:30:47: 33:27] : std::clone::Clone`

查看我看到的文档:

impl<I, U, F> Clone for FlatMap<I, U, F>
    where F: Clone, I: Clone, U: Clone + IntoIterator, U::IntoIter: Clone

impl<I, U, F> Iterator for FlatMap<I, U, F>
    where F: FnMut(I::Item) -> U, I: Iterator, U: IntoIterator

看起来 F 同时受 Clone 特征和 FnMut 特征的约束,但不可能同时实现 FnMutClone.

文档中存在无法调用的方法,这似乎很奇怪,所以我一定是遗漏了什么。

有人可以为我澄清一下吗?

MVCE:

fn main() {
    let possible_children = (0..10).flat_map(|x| (0..10).map(|y| (x,y)));

    let causes_error = possible_children.clone().flat_map(|a|
        possible_children.clone().map(|b| (a,b) )
    ).collect();

    println!("{:?}",causes_error);
}

一个类型不能同时实现 FnMutClone 并没有内在的原因,但目前闭包似乎没有实现 Clone。这是一个简短的 discussion about this from 2015。我(还)没有找到更多最近的讨论。

我能够构建这个示例,其中通过在我自己的结构上实现 FnMut 来克隆 FlatMap,这需要不稳定的功能,所以夜间编译器(playground):

#![feature(unboxed_closures)]
#![feature(fn_traits)]
struct MyFun {
    pub v: usize,
}

impl FnOnce<(usize,)> for MyFun {
    type Output = Option<usize>;
    extern "rust-call" fn call_once(self, args: (usize,)) -> Self::Output {
        Some(self.v + 1 + args.0)
    }

}

impl FnMut<(usize,)> for MyFun {
    extern "rust-call" fn call_mut(&mut self, args: (usize,)) -> Self::Output {
        self.v += 1;
        if self.v % 2 == 0 {
            Some(self.v + args.0)
        } else {
            None
        }
    }
}

impl Clone for MyFun {
    fn clone(&self) -> Self {
        MyFun{v: self.v}
    }
}

fn main() {
    let possible_children = (0..10).flat_map(MyFun{v:0});
    let pairs = possible_children.clone().flat_map(|x| possible_children.clone().map(move |y| (x,y) ) );
    println!("possible_children={:?}", pairs.collect::<Vec<_>>());
}

您正在一个迭代器中创建项目集与另一个项目集的笛卡尔积。您可以为此使用 .cartesian_product() adaptor from the itertools 板条箱。