首页 > 解决方案 > 修改未在该结构的 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;
            }
        }

标签: rust

解决方案


推荐阅读