在下面的代码中,我了解到通过调用已完成了借用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句