To learn about Weak ref in Rust, I wrote the following code. The main thing is a Factory and a Car. use a Factory to weak ref to some of the cars it produces, and these Car always ref to the Factory that produced it.
Now I want to implement a Factory.make_car() function that creates a car object that implements the above reference relationship.
But while writing this function, I ran into a difficulty. Because the parameter of make_car() is a &mut of Factory object, how can I get the Rc<Factory> object?
That is, how to modify the following ???? so that the program can compile successfully?
struct Factory {
cars: Vec<Weak<Car>>,
}
struct Car {
fact: Rc<Factory>,
}
impl Factory {
pub fn make_car(&mut self) -> Car {
let car = Car { fact: Rc::clone(???), };
let carc = Rc::new(car);
self.cars.push(Rc::downgrade(&carc));
return car;
}
}
#[cfg(test)]
pub mod tests {
#[test]
fn test_make_car() {
let mut factory = super::Factory{cars: vec![]};
let car = factory.make_car();
}
}