rust - 当代码不是时,Rust 编译器抱怨在循环中使用移动值
问题描述
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
,然后再也不会使用。为什么这是编译器错误?
有趣的是,以下替代方法有效:
Some(a) if a != x => {
outs.push(a);
stage = Some(x);
}
_ => {}
解决方案
当你写
match stage {
// ...
Some(a) => {
// ...
}
}
您无条件地将值移出stage
. 块中的代码是否使用都a
没有关系;Rust 所看到的stage
只是现在无效,不能再次使用。
之所以
Some(a) if a != x => {
outs.push(a);
stage = Some(x);
}
有效是因为if
在模式中包含 使其成为有条件的移动。只有在时a
才会移出a != x
,并且当这种情况发生时,stage
总是会重新分配。
推荐阅读
- artifactory - 从 6.0.2 升级到 Artifactory 6.9.1 后无法请求元数据服务 Service-Id
- c - 负数的 C++ 左移溢出
- python - pyspark Dataframe - 截断十进制列
- asp.net-core - Azure DevOps 忽略了一个项目的 Publish
- javascript - 为什么复制的数组之间存在关系?
- spring-boot - 我们如何将 Springboot 2.x 与 Zuul 2 集成
- python - 为什么当用户注销时,任务调度程序无法与执行带有 selenium 的 python 程序的批处理文件完全交互
- git - 如何更改子模块的名称?
- python - SARIMAX:增量卡尔曼滤波器
- python - 无法在 json 上插入新行