Rust在循环中使用了已移动的值,导致出现错误提示:
错误信息是:
当我阅读这段代码时,我看到
#[derive(PartialEq, Eq)]
enum Animal {
Dog,
Cat,
}
fn dedup(animals: Vec<Animal>) -> Vec<Animal> {
let mut stage = None;
let mut outs = vec![];
for x in animals {
match stage {
None => stage = Some(x),
Some(a) => {
if a != x {
outs.push(a);
stage = Some(x);
}
}
}
}
if let Some(a) = stage {
outs.push(a);
}
outs
}
错误信息是:
error[E0382]: use of moved value
--> src/lib.rs:14:18
|
14 | Some(a) => {
| ^ value moved here, in previous iteration of loop
|
当我阅读这段代码时,我看到
stage
被移动到a
中,然后可能被推送到outs
中,然后再也没有被使用。为什么这会导致编译错误?
Playground
有趣的是,以下替代方案可以正常工作: Some(a) if a != x => {
outs.push(a);
stage = Some(x);
}
_ => {}
outs.last()
来编写不带阶段的dedup
(playground)。当然,如果这不是一个练习,你应该直接调用Vec::dedup
。 - trent