Let's have a struct containing a vector of cities and a new_city function adding City to the vector. However, I got BorrowMutError which makes sense.
What should I do so I can call new_city multiple times (see below)? I would need to drop the borrow_mut reference in the new_city function but I don't know how.
//use std::rc::Rc;
use std::cell::RefCell;
use std::cell::Ref;
pub struct Simulation{
cities: RefCell<Vec<City> >,
}
impl Simulation{
pub fn new() -> Simulation
{
Simulation{
cities: RefCell::new(Vec::new()),
}
}
pub fn new_city(&self, name: &'static str) -> Ref<City> {
let city = City::new(name);
self.cities.borrow_mut().push(city);
Ref::map(self.cities.borrow(), |vec| vec.last().unwrap())
}
}
#[derive(Debug, Copy, Clone)]
pub struct City {
name: &'static str,
}
impl City{
pub fn new(name: &'static str) -> City {
City { name: name, }
}
}
fn main(){
let mut simulation = Simulation::new();
let prg = simulation.new_city("Prague");
let brn = simulation.new_city("Brno");
let pls = simulation.new_city("Pilsen");
println!("{:?}", prg);
}
EDIT: Next use
Then I need prg and brn cities to add road between them with API (another vector in Simulation)
pub fn new_road(&self, from: &City, to: &City, time: i32) -> &Road {
//Adding information about road to simulation
}
let d1 = simulation.new_road(&prg, &brn, 120);
Therefore I cannot drop prg or brn.