首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用borrow_mut向矢量方向推锈

用borrow_mut向矢量方向推锈
EN

Stack Overflow用户
提问于 2022-12-01 14:14:24
回答 1查看 34关注 0票数 0

让我们有一个包含城市向量的结构和一个将City添加到向量中的new_city函数。然而,我得到了BorrowMutError,这是有道理的。

我应该怎么做才能多次调用new_city (见下文)?我需要在borrow_mut函数中删除new_city引用,但我不知道如何删除。

代码语言:javascript
复制
//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 (另一个模拟向量)在它们之间添加道路。

代码语言:javascript
复制
pub fn new_road(&self, from: &City, to: &City, time: i32) -> &Road {
         //Adding information about road to simulation
}
代码语言:javascript
复制
let d1 = simulation.new_road(&prg, &brn, 120);

因此,我不能放弃prg或brn。

EN

回答 1

Stack Overflow用户

发布于 2022-12-01 14:20:51

您可以简单地引入一个新的作用域,在其末尾删除BorrowMut

代码语言:javascript
复制
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

代码语言:javascript
复制
fn main() {
    let mut simulation = Simulation::new();
    let prg = simulation.new_city("Prague");
    drop(prg);
    let brn = simulation.new_city("Brno");
}

您可能希望将这些城市封装在Rcs中,以便能够在pushes中保存它们:

代码语言:javascript
复制
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()
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74643269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档