A simplified version of what I'd like to achieve:
I previously used Rc<RefCell<A>>
but I was wondering if I could avoid that altogether and work with references instead. The child struct should be able to mutate the parent struct, but the two will never attempt to mutate within the same scope.
struct A<'parent> {
parent_a: Option<&'parent mut A<'parent>>,
field: i32,
}
impl<'parent> A<'parent> {
pub fn new() -> Self {
A{parent_a: None, field: 0}
}
pub fn new_from_parent(parent_a: &'parent mut A<'parent>) -> Self {
A{parent_a: Some(&mut *parent_a), field: 0}
}
}
fn main() {
let mut outer = A::new();
{ // Enter some sort of scope, like function where outer is a param
let mut inner = A::new_from_parent(&mut outer);
inner.field = 1;
} // I want the borrow to end here but the lifetime of the borrow is as long as the original
println!("{}", outer.field); // Does not compile since mutable borrow above, immutable borrow here
}
How can I indicate the duration of the borrow? I'm OK with the child struct living as long as the parent struct if it needs to, but I'd also like the mutable borrow to be dropped when the child struct has gone out of scope.