Search code examples
vectorrustreferencemutability

How to get mutable reference to object inside vec inside a struct in rust?


I have a very basic problem in a rust relating to mutability of objects inside a vector. I have a need to get a mutable reference to an object from within a method of the struct as follows:

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
}

I cannot change the function to use &mut self because this requirement is forced by a trait I'm trying to implement here. What is a proper way to get around this kind of issue? I need to be able to modify the data in those regions inside the Vec in the struct.


Solution

  • You need to use RefCell, or Mutex if it is shared between threads

    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
    }
    

    You can find more info here https://doc.rust-lang.org/book/ch15-05-interior-mutability.html