Sorry for the complex title, it's difficult to summarize my problem. Here it is :
I wish to iterate over a Vec of struct and modifiy elements in the process. But my struct has a Vec and Vec dosen't implement Copy. I tried many things but I never succeed. And I think it's because I don't realy understand the problem...
A naive exemple :
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]`
ANSWER : Thanks to trentcl to solve this with adding &mut to iterator and simplified the case, I was going too complex. Playgroud here.
for o in &mut objs{
if o.id == 1 || o.id == 2 {
o.activated = true;
}
}