Hi Rustaceans!
Is there some pattern that allows mutable and shared references on the same object at the same time, when those references are held on disjoint fields within the containing type?
I'm aware of interior mutability types like Cell
and RefCell
, however I was hoping there would be a lifetime related solution considering they are disjoint, as neither of those interior mutability allow a direct shared reference (i.e. &T
) to be taken.
(See playground).
struct First<T> { value: T }
struct Second<T> { value: T }
struct Foo<T> {
first: First<T>,
second: Second<T>,
}
impl<T> First<T> {
fn get_mut(&mut self) -> &mut T {
&mut self.value
}
}
impl<T> Second<T> {
fn get(&self) -> &T {
&self.value
}
}
impl<T> Foo<T> {
fn get_first_mut(&mut self) -> &mut T {
self.first.get_mut()
}
fn get_second(&self) -> &T {
self.second.get()
}
}
fn main() {
let mut x = Foo {
first: First { value: 123 },
second: Second { value: 123 },
};
// This is fine:
{
let a = x.first.get_mut();
let b = x.second.get();
println!("{} {}", a, b);
}
// This has first borrowed mutable when second is attempted.
{
let a = x.get_first_mut();
let b = x.get_second();
println!("{} {}", a, b);
}
}