gpt4 book ai didi

rust - 了解在两次调用迭代器上的方法时如何满足借用检查器?

转载 作者:行者123 更新时间:2023-12-03 11:29:34 25 4
gpt4 key购买 nike

在下面的代码中,我了解到借用已通过调用 zipped.filter 完成。 .我不明白的是如何修复它,如果我想使用 zipped稍后再试。
我是 Rust 的新手,所以如果这段代码中存在其他问题或奇怪的习语误用,我也对此很感兴趣,但主要是关于如何使借用在这里工作两次。
代码:

fn main() {
let data : Vec<String> = vec!["abc".to_string(), "def".to_string(), "bbc".to_string()];

for s1 in &data {
for s2 in &data {
let zipped = s2.chars().zip(s1.chars());

// Did a diff of the two strings have only one character different?
if zipped.filter(|(a,b)| a != b).count() == 1 {
let newStr = zipped.filter(|(a,b)| a == b).map(|(a,_)| a).collect::<String>();

println!("String without the different character: {}", newStr);
}
}
}
}
错误:
error[E0382]: use of moved value: `zipped`
--> a.rs:10:30
|
6 | let zipped = s2.chars().zip(s1.chars());
| ------ move occurs because `zipped` has type `Zip<Chars<'_>, Chars<'_>>`, which does not implement the `Copy` trait
...
9 | if zipped.filter(|(a,b)| a != b).count() == 1 {
| ---------------------- `zipped` moved due to this method call
10 | let newStr = zipped.filter(|(a,b)| a == b).map(|(a,_)| a).collect::<String>();
| ^^^^^^ value used here after move
|
note: this function consumes the receiver `self` by taking ownership of it, which moves `zipped`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.

最佳答案

您可以随时zipped.clone() ,它会克隆迭代器,以便您在第一次调用 filter(...).count() 时移动克隆。 .原版zipped保持不变,您将移动它第二个 filter(...).collect() .
请注意,它不会克隆任何数据,因为迭代器是惰性的,复制迭代器意味着复制其逻辑(因此它复制 .chars().zip() 等的逻辑,这些逻辑只是一堆函数指针,而不是数据)。

fn main() {
let data : Vec<String> = vec!["abc".to_string(), "def".to_string(), "bbc".to_string()];

for s1 in &data {
for s2 in &data {
let zipped = s2.chars().zip(s1.chars());

// << THE CHANGE IS HERE
if zipped.clone().filter(|(a,b)| a != b).count() == 1 {
let newStr = zipped.filter(|(a,b)| a == b).map(|(a,_)| a).collect::<String>();

println!("String without the different character: {}", newStr);
}
}
}
}
输出:
String without the different character: bc
String without the different character: bc

关于rust - 了解在两次调用迭代器上的方法时如何满足借用检查器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65570580/

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