修改在循环的Vec上未实现复制特征的结构

时间:2020-03-19 17:39:18

标签: rust

抱歉,标题很复杂,很难总结我的问题。这是:

我希望在此过程中遍历结构和修改元素的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>,
}

Playground

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添加到迭代器来解决此问题并简化了案例,我变得太复杂了。 Playgroud here

        for o in &mut objs{
            if o.id == 1 || o.id == 2 {
                o.activated = true;
            }
        }

0 个答案:

没有答案
相关问题