I have a struct containing a vector whose elements must be able to modify other elements in the vector.
I tried doing it like this:
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]);
}
However , I got these errors
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>>`
How do I get this done? also please note that Due to some constraints , I do not want to create any extra variables in the main function.
The attack function works like an update function for different elements of the vec in the main program I am supposed to be running