让我们有一个包含城市向量的结构和一个将City添加到向量中的new_city函数。然而,我得到了BorrowMutError,这是有道理的。
我应该怎么做才能多次调用new_city (见下文)?我需要在borrow_mut函数中删除new_city引用,但我不知道如何删除。
//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);
}编辑:下一步使用
然后,我需要prg和brn城市使用API (另一个模拟向量)在它们之间添加道路。
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);因此,我不能放弃prg或brn。
发布于 2022-12-01 14:20:51
您可以简单地引入一个新的作用域,在其末尾删除BorrowMut:
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())
}但是,您也不能通过Ref调用来保存new_city。
fn main() {
let mut simulation = Simulation::new();
let prg = simulation.new_city("Prague");
drop(prg);
let brn = simulation.new_city("Brno");
}您可能希望将这些城市封装在Rcs中,以便能够在pushes中保存它们:
pub struct Simulation{
cities: RefCell<Vec<Rc<City>>>,
}
//...
impl Simulation {
//...
pub fn new_city(&self, name: &'static str) -> Rc<City> {
{
let city = Rc::new(City::new(name));
self.cities.borrow_mut().push(city);
}
self.cities.borrow().last().unwrap().clone()
}
}https://stackoverflow.com/questions/74643269
复制相似问题