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

r1zk6ea1  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(136)

我在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内部那些区域中的数据。

j9per5c4

j9per5c41#

您需要使用RefCell,或者如果在线程之间共享互斥锁,则需要使用互斥锁

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

相关问题