rust - 修改未在该结构的 Vec 上循环实现复制特征的结构
问题描述
抱歉标题复杂,很难总结我的问题。这里是 :
我希望在该过程中迭代结构和修改元素的 Vec。但是我的结构有一个 Vec 并且 Vec 没有实现 Copy。我尝试了很多东西,但我从来没有成功过。我认为这是因为我真的不明白这个问题......
一个天真的例子:
fn main() {
let obj_0 = Obj{id: 0, activated: false, obj_list: [1].to_vec()};
let obj_1 = Obj{id: 1, activated: false, obj_list: [].to_vec()};
let obj_2 = Obj{id: 2, activated: false, obj_list: [0, 1].to_vec()};
let obj_3 = Obj{id: 3, activated: false, obj_list: [2, 4].to_vec()};
let obj_4 = Obj{id: 4, activated: false, obj_list: [0,1,2].to_vec()};
let obj_5 = Obj{id: 5, activated: false, obj_list: [1].to_vec()};
let mut objs: Vec<Obj> = [obj_0, obj_1, obj_2, obj_3, obj_4, obj_5].to_vec();
//loop {
objs[0].activated = true;
for o in objs{
if o.id == 1 || o.id == 2 {
let mut o2 = objs[o.id];
o2.activated = true;
objs[o.id] = o2;
}
}
//}
}
#[derive (Clone)]
struct Obj {
id: usize,
activated: bool,
obj_list: Vec<i32>,
}
(游乐场)
error[E0382]: borrow of moved value: `objs`
--> src/lib.rs:14:30
|
8 | let mut objs: Vec<Obj> = [obj_0, obj_1, obj_2, obj_3, obj_4, obj_5].to_vec();
| -------- move occurs because `objs` has type `std::vec::Vec<Obj>`, which does not implement the `Copy` trait
...
12 | for o in objs{
| ----
| |
| value moved here
| help: consider borrowing to avoid moving into the for loop: `&objs`
13 | if o.id == 1 || o.id == 2 {
14 | let mut o2 = objs[o.id];
| ^^^^ value borrowed here after move
error[E0507]: cannot move out of index of `std::vec::Vec<Obj>`
--> src/lib.rs:14:30
|
14 | let mut o2 = objs[o.id];
| ^^^^^^^^^^
| |
| move occurs because value has type `Obj`, which does not implement the `Copy` trait
| help: consider borrowing here: `&objs[o.id]`
回答:感谢 trentcl 通过向迭代器添加 &mut 来解决这个问题并简化了案例,我太复杂了。游乐场在这里。
for o in &mut objs{
if o.id == 1 || o.id == 2 {
o.activated = true;
}
}
解决方案
推荐阅读
- r - 将 ggrepel 长标签移动到绘图线的右侧
- python-3.x - [range(5)] 和 list(range(5)) 之间的区别
- scala - 如何在scala中一张一张地合并或插入两张地图?
- c - 为什么这两个 execvp 会产生不同的结果?
- angularjs - 不显示日按钮和周按钮
- scala - Spark Scala groupBy(cols).agg( 20 个 sum 函数),如何使用 map 简化 20 个 agg 函数?
- asp.net-core - 如何使用带有 OData v4 的 .NET Core WebAPI 过滤 SQL Server DateTime
- excel - 具有 3 个标准的索引/总和
- javascript - 为什么有些内置的 javascript 方法是静态的,而有些不是?
- vba - 如何使用 Access VBA 更新所有 ODBC 链接的 SQL Server 表的服务器名称