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

Mic*_*iff 7 clone rust flatmap

我试图创建所有可能的项目对FlatMap:

possible_children.clone().flat_map(|a| possible_children.clone().map(|b| (a,b)))
Run Code Online (Sandbox Code Playgroud)

为了做到这一点,我试图克隆一个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`
Run Code Online (Sandbox Code Playgroud)

看看我看到的文档:

impl<I, U, F> Clone for FlatMap<I, U, F>
    where F: Clone, I: Clone, U: Clone + IntoIterator, U::IntoIter: Clone
Run Code Online (Sandbox Code Playgroud)

impl<I, U, F> Iterator for FlatMap<I, U, F>
    where F: FnMut(I::Item) -> U, I: Iterator, U: IntoIterator
Run Code Online (Sandbox Code Playgroud)

它看起来像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);
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*son 8

有一个类型不能同时实现没有内在的原因FnMutClone,但似乎在一瞬间关闭不执行Clone.以下是2015年对此的简要讨论.我还没有(还)找到最近的讨论.

我能够FlatMap通过FnMut在我自己的struct上实现克隆来构建这个例子,这需要不稳定的特性,所以每晚编译器(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<_>>());
}
Run Code Online (Sandbox Code Playgroud)