Hello, I'm trying to use a data schema like this:
use std::cell::RefCell;
use std::rc::Rc;
struct Little {
little_counter: i32,
}
impl Little {
fn do_stuff(&self, api: Rc<RefCell<Api>>) {
api.borrow_mut().sum(); <- ///// error here ////// 8
}
}
struct Api {
littles: Vec<Little>,
}
impl Api {
fn new() -> Rc<RefCell<Self>> {
let new_littles = vec![Little { little_counter: 0 }];
Rc::new(RefCell::new(Self {
littles: new_littles,
}))
}
fn sum(&mut self) {
for val in self.littles.iter_mut() {
val.little_counter += 1;
}
}
fn show(&self) {
for val in self.littles.iter() {
println!("{}", val.little_counter);
}
}
}
struct Big {
api: Rc<RefCell<Api>>,
}
impl Big {
pub fn new() -> Self {
Self { api: Api::new() }
}
pub fn do_littles(&self, api: Rc<RefCell<Api>>) {
for (i, _) in self.api.clone().borrow().littles.iter().enumerate() {
api.borrow().littles[i].do_stuff(self.api.clone());
}
}
}
fn main() {
let big = Big::new();
big.do_littles(big.api.clone());
big.api.clone().borrow().show();
}
The deal here is that i'm trying to pass the "Api" to do_stuff,
This Api changes "littles" which is an Vec of "Little".
So every Little should be able to change the counter in any other Little's including itself.
I have been trying pretty much everything but still i'm in constant fight with the borrow checker because i can't have two mutable references of the Api at one. For example here the problem is.
thread 'main' panicked at 'already borrowed: BorrowMutError', src/main.rs:9:13
expected behaviour:
1
Because there's only one "Little" and it's counter is 0,
and then here
big.do_littles(big.api.clone());
It's set to 1 (sums 1 to the counter for each Little that runs "do_stuff")
I have spent 2 entire days and still found no solution
Thanks for reading!