gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:46:05 31 4
gpt4 key购买 nike

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com