如何在rust中获取对结构中vec内部对象的可变引用



在一个与向量内对象的可变性有关的rust中,我有一个非常基本的问题。我需要从结构的方法中获得对对象的可变引用,如下所示:

struct Allocator {
free_regions: Vec<Region>, // vec of free regions
used_regions: Vec<Region>, // vec of used regions
}
fn alloc(&self, layout: Layout) -> ! {
//I want to get this mutable reference in order to avoid copying large amount of data around
let region: &mut Region = self.free_regions.get_mut(index).expect("Could not get region");
//This fails with  `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
}

我不能将函数更改为使用&mut self,因为这个需求是我试图在这里实现的一个特性所强制的。解决这类问题的正确方法是什么?我需要能够修改结构中Vec内部那些区域中的数据。

如果在线程之间共享,则需要使用RefCell或Mutex

struct Allocator {
free_regions: RefCell<Vec<Region>>, // vec of free regions
used_regions: RefCell<Vec<Region>>, // vec of used regions
}
fn alloc(&self, layout: Layout) -> ! {
//I want to get this mutable reference in order to avoid copying large amount of data around
let region: &mut Region = self.free_regions.borrow_mut().get_mut(index).expect("Could not get region");
//This fails with  `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
}

你可以在这里找到更多信息https://doc.rust-lang.org/book/ch15-05-interior-mutability.html

最新更新