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

标签 rust clone flatmap

我正在尝试在 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

看起来 FClone trait 和 FnMut trait 绑定(bind),但是不可能同时实现这两个FnMut克隆

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

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

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<_>>());
}

关于rust - std::iter::FlatMap.clone() 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303790/

相关文章:

Java 流 flatMap 将第一级和第二级对象保留在流中

rust - 有条件地在Rust中对Vec进行排序

docker - Docker 镜像上的 pip 找不到 Rust - 即使安装了 Rust

rust - 为什么需要使用加号运算符 (Iterator<Item = &Foo> + 'a) 为特征添加生命周期?

git - 如何在分支中使用外部链接存储库进行 git 克隆?

android - 使用RxJava,Retrofit,RxKotlin平面图依次调用多个API

rust - 我怎样才能拥有一个仅用于其内部常量的结构?

java - 使用和不使用 Cloneable 覆盖克隆

c - 在 clone() 之后通过指针访问父级中的变量

scala - flatMap 究竟做了什么?