1

我有一个包含向量的结构,其元素必须能够修改向量中的其他元素。

我试着这样做:

use core::cell::RefCell;

struct Go {
    car: i32,
}

impl Go {
    pub fn attack(&mut self, val: &mut Self) {
        val.car = self.car;
        self.car = 5;
    }
}

struct World {
    pub params: RefCell<Vec<Go>>,
    pub val: i32,
}

fn main() {
    let world = World {
        params: RefCell::new(vec![]),
        val: 42,
    };

    for m in 0..10 {
        world.params.borrow_mut().push(Go { car: m });
    }

    world.params.borrow()[5].attack(&mut world.params.borrow()[6]);
}

操场

但是,我收到了这些错误

error[E0596]: cannot borrow data in a dereference of `std::cell::Ref<'_, std::vec::Vec<Go>>` as mutable
  --> src/main.rs:29:5
   |
29 |     world.params.borrow()[5].attack(&mut world.params.borrow()[6]);
   |     ^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `std::cell::Ref<'_, std::vec::Vec<Go>>`

error[E0596]: cannot borrow data in a dereference of `std::cell::Ref<'_, std::vec::Vec<Go>>` as mutable
  --> src/main.rs:29:42
   |
29 |     world.params.borrow()[5].attack(&mut world.params.borrow()[6]);
   |                                          ^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
   |
   = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `std::cell::Ref<'_, std::vec::Vec<Go>>`

我该怎么做?另请注意,由于某些限制,我不想在主函数中创建任何额外的变量。

攻击功能就像我应该运行的主程序中 vec 的不同元素的更新功能一样

4

0 回答 0