Suppose I have a struct that hols polynomials, and I want to access some mutably, and other non mutably:
pub struct Poly{}
pub struct PolyCollection{
polys: Vec<Poly>
}
impl PolyCollection {
fn get_poly(&self, index: usize) -> Option<&Poly>{
self.polys.get(index)
}
fn get_poly_mut(&mut self, index: usize) -> Option<&mut Poly>{
self.polys.get_mut(index)
}
}
fn use_polys(poly1: &Poly, poly2: &mut Poly) {
todo!()
}
fn do_something(poly_collection: &mut PolyCollection) {
use_polys(poly_collection.get_poly(0).unwrap(),
poly_collection.get_poly_mut(1).unwrap())
}
I obviously get:
error[E0502]: cannot borrow `*poly_collection` as mutable because it is also borrowed as immutable
--> src/lib.rs:24:9
|
23 | use_polys(poly_collection.get_poly(0).unwrap(),
| --------- --------------------------- immutable borrow occurs here
| |
| immutable borrow later used by call
24 | poly_collection.get_poly_mut(1).unwrap())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
which could have, as a solution, doing:
polys: Vec<RefCell<Poly>>
but is there a more elegant way of doing so, without having to deal with potential panics on borrow mut + borrow?
I was thinking about something like slice.chunks_mut()
, but chunks_mut is for iterators.